#RequestMapping not redirecting to the specified URL : Spring Boot application - spring

I am trying to create a sample spring boot application which can connect to postgres. But I am not able to redirect to the path specified in the rest controller. The code for my project is given below:
pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.vmware.springboot</groupId>
<artifactId>SpringBootSample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBootDemo1</name>
<description>Sample project for Spring Eureka</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=3000
spring.datasource.url= jdbc:postgresql://localhost:5432/local_db
spring.datasource.data-username=postgres
spring.datasource.data-password=postgres
spring.jpa.hibernate.ddl-auto=create-drop
SpringBootExampleApplication.java
package org.kumar.springboot;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.kumar.spring.enitiy.Employee;
#SpringBootApplication
#ComponentScan
public class SpringBootExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootExampleApplication.class, args);
}
}
EmployeeController.java
package org.kumar.spring.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.kumar.spring.enitiy.Employee;
import org.kumar.spring.repository.EmployeeRepository;
#RestController
#RequestMapping("/data")
public class EmployeeController {
#Autowired
private EmployeeRepository employeeRepository;
#RequestMapping("/employees")
public List<Employee> getEmployees(){
return (List<Employee>)employeeRepository.findAll();
}
}
Employee.java
package org.kumar.spring.enitiy;
public class Employee {
private String employeeId;
private String employeeName;
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
#Override
public String toString() {
return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + "]";
}
public Employee(String employeeId, String employeeName) {
super();
this.employeeId = employeeId;
this.employeeName = employeeName;
}
}
EmployeeRepository.java
package org.kumar.spring.repository;
import org.springframework.data.repository.CrudRepository;
import org.kumar.spring.enitiy.Employee;
public interface EmployeeRepository extends CrudRepository<Employee, String>
{
}
I am trying to run the following:
Request : GET http://localhost:3000/data/employees
Response :
{
"timestamp": 1492152367659,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/data/employees"
}
What mistake am I committing.

Basically, your EmployeeController class has not been detected/scanned by the Spring container because of the classes are in different package hierarchy and the container has not been instructed to scan in which package to look for.
So there are two options to solve the issue:
(1) Change your SpringBootExampleApplication class package to org.kumar.spring
(2) Add #ComponentScan(basePackages = {"org.kumar.spring"})
I suggest you prefer the option(1) above otherwise, for option(2), you need to add #EnableJpaRepositories to make the program to work from end to end (i.e., connecting to the database using your EmployeeRepository class).

Related

Getting null value while fetching properties from application.properties file in Springboot

Objective : reading property value from application.properties file in my Java class .
Current behaviour : getting null values
Expected behaviour :
value1
value3
application.properties
category1.subcategory2=value1
category1.subcategory3=value3
greeting.salutation=Hello
TryValueApplication.java
package com.example.tryvalue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TryValueApplication {
#Value("${category1.subcategory2}")
private String category1;
#Value("basic value")
private String category3;
public static void main(String[] args) {
SpringApplication.run(TryValueApplication.class, args);
TryValueApplication tryValueApplication = new TryValueApplication();
System.out.println("Running main method");
tryValueApplication.printCategory();
}
public void printCategory(){
System.out.println("Print environment values");
System.out.println(category1);
System.out.println(category3);
}
}
Tried :
I tried accessing same value from within #RestController class and it was working .
GreetingController.java
package com.example.tryvalue.controller;
import com.example.tryvalue.EnvironmentValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class GreetingController {
#Value("${greeting.salutation}")
private String greetingSalutation;
#Autowired
private EnvironmentValue environmentValue;
#GetMapping
public String greeting(){
return greetingSalutation + " world";
}
#GetMapping("/category1")
public String getCategory1(){
return environmentValue.getCategory1();
}
}
EnvironmentValue.java
package com.example.tryvalue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class EnvironmentValue {
#Value("${category1.subcategory2}")
private String category1;
#Value("${category1.subcategory3}")
private String category2;
#Value("basic value")
private String category3;
public EnvironmentValue(){
System.out.println("Creating instance of EnvironmentValue");
}
public String getCategory1(){
return category1;
}
public String getCategory2(){
return category2;
}
public String getCategory3(){
return category3;
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>tryValue</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>tryValue</name>
<description>tryValue</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
What can be the reason behind this difference in behaviour ?
Thanks .
You are creating a second unmanaged instance of TryValueApplication in your main method so the properties won't be injected into that.
The managed instance of TryValueApplication should have the values injected. Add this to TryValueApplication to print the values
#Value("${category1.subcategory2}")
private String category1;
#Value("${category1.subcategory3}")
private String category3;
public static void main(String[] args) {
SpringApplication.run(TryValueApplication.class, args);
}
#PostConstruct
public void printCategory(){
System.out.println("Print environment values");
System.out.println(category1);
System.out.println(category3);
}

The request resource is not available - Spring, Hibernate, mvn

If we look into the StudentController, request mapping is #RequestMapping("/rest") for class
and get mapping is #GetMapping("/test").
Hence for url http://localhost:8080/TestHibernate/rest/test, I should get a string 'success', which I am not getting.
On executing url http://localhost:8080/TestHibernate I am getting the content placed in index file.
Please let me know what part I am missing.
Thank you.
Controller class
package com.akshay.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.akshay.dao.StudentDAO;
import com.akshay.entity.Student;
#RestController
#RequestMapping("/rest")
public class StudentController {
#Autowired
private StudentDAO studentDAO;
#PostMapping("/saveStudent")
public String save(#RequestBody Student student) {
studentDAO.saveStudent(student);
return "Saved Successfully";
}
#GetMapping("/test")
public String test() {
return "Success";
}
}
DAO Layer
package com.akshay.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.akshay.entity.Student;
#Repository
#Transactional
public class StudentDAO {
#Autowired
private SessionFactory factory;
private Session getSession() {
Session session = factory.getCurrentSession();
if(session == null) {
session = factory.openSession();
}
return session;
}
public void saveStudent(Student student) {
getSession().save(student);
}
}
Entity Layer
package com.akshay.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
public Student() {
}
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
Entry Point
package com.akshay.TestHibernate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TestHibernateApplication {
public static void main(String[] args) {
SpringApplication.run(TestHibernateApplication.class, args);
}
}
POM file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.akshay</groupId>
<artifactId>TestHibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>TestHibernate</name>
<description>Demo project to test hibernate and mysql</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<!--<scope>provided</scope> -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
#
# JDBC connection properties
#
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/web_student_tracker
jdbc.user=springstudent
jdbc.password=springstudent
#
# Connection pool properties
#
connection.pool.initialPoolSize=5
connection.pool.minPoolSize=5
connection.pool.maxPoolSize=20
connection.pool.maxIdleTime=3000
#
# Hibernate properties
#
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.packagesToScan=com.akshay.entity
Introduction
Let's consider the following versions as the current versions:
Spring Boot: 2.7.1.
Analysis
Please, note that the package of the controller class (com.akshay.controller.StudentController) is not the same as the package of the application class (com.akshay.TestHibernate.TestHibernateApplication).
Let's refer to the documentation: Developing with Spring Boot: 6. Using the #SpringBootApplication Annotation:
Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their "application class". A single #SpringBootApplication annotation can be used to enable those three features, that is:
#EnableAutoConfiguration: enable Spring Boot’s auto-configuration mechanism
#ComponentScan: enable #Component scan on the package where the application is located (see the best practices)
#SpringBootConfiguration: enable registration of extra beans in the context or the import of additional configuration classes. An alternative to Spring’s standard #Configuration that aids configuration detection in your integration tests.
Please, note:
#ComponentScan: enable #Component scan on the package where the application is located (see the best practices)
Solution
It is necessary to add the controller package to be component-scanned.
For example:
<…>
#SpringBootApplication
#ComponentScan(basePackages="com.akshay.controller")
public class TestHibernateApplication {
<…>
Test the controller method execution by performing an HTTP request:
curl -X GET http://localhost:8080/rest/test
Additional references
Stack Overflow question. java - Spring Boot: Cannot access REST Controller on localhost (404) - Stack Overflow.

Error creating bean with name 'activityController'

I'm having this problem while running on Server (Tomcat) my project. I have created a Maven project using Spring. The Java version is Java 1.8.
NO SPRING-BOOT!
Error creating bean with name 'activityController': Unsatisfied dependency expressed through field 'activityService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'activityService': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.calendar.repository.ActivityDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Could you please help me? Thank you!
This is the code.
Thank you!!!
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.calendar</groupId>
<artifactId>calendar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Calendar</name>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>5.1.4.RELEASE</springframework.version>
<jackson.version>2.11.2</jackson.version>
<email.version>1.6.2</email.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.0</version>
</dependency>
</dependencies>
<repositories>
</repositories>
<build>
<finalName>company-calendar</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Activity.java
package com.calendar.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.List;
/**
* The persistent class for the activity database table.
*
*/
#Entity
#NamedQuery(name = "Activity.findAll", query = "SELECT a FROM Activity a")
public class Activity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Integer id;
#Column(name = "create_time")
private Timestamp createTime;
#Column(name = "created_by")
private String createdBy;
private String description;
#Column(name = "update_time")
private Timestamp updateTime;
#Column(name = "updated_by")
private String updatedBy;
//bi-directional many-to-one association to CalendarHeader
#OneToMany(mappedBy = "activity")
private List<CalendarHeader> calendarHeaders;
public Activity() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Timestamp getCreateTime() {
return this.createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
public String getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
public List<CalendarHeader> getCalendarHeaders() {
return this.calendarHeaders;
}
public void setCalendarHeaders(List<CalendarHeader> calendarHeaders) {
this.calendarHeaders = calendarHeaders;
}
public CalendarHeader addCalendarHeader(CalendarHeader calendarHeader) {
getCalendarHeaders().add(calendarHeader);
calendarHeader.setActivity(this);
return calendarHeader;
}
public CalendarHeader removeCalendarHeader(CalendarHeader calendarHeader) {
getCalendarHeaders().remove(calendarHeader);
calendarHeader.setActivity(null);
return calendarHeader;
}
}
ActivityDAO.java
package com.calendar.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.calendar.entity.Activity;
#Repository
public interface ActivityDAO extends JpaRepository<Activity, Integer> {}
**ActivityDTO.java**
package com.calendar.dto;
import java.sql.Timestamp;
public class ActivityDTO {
private Integer id;
private String description;
private Timestamp createTime;
private String createdBy;
private Timestamp updateTime;
private String updatedBy;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getCreateTime() {
return createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Timestamp getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
ActivityService.java
package com.calendar.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.calendar.dto.ActivityDTO;
import com.calendar.repository.ActivityDAO;
import com.calendar.entity.Activity;
#Service
public class ActivityService {
#Autowired
ActivityDAO dao;
public List<ActivityDTO> findAll() {
List<ActivityDTO> DTOList = new ArrayList<ActivityDTO>();
List<Activity> entity = dao.findAll();
if (entity != null) {
for (Activity e : entity) {
DTOList.add(getDTOFromEntity(e));
}
}
return DTOList;
};
protected ActivityDTO getDTOFromEntity(Activity entity) {
ActivityDTO activityDTO = new ActivityDTO();
activityDTO.setId(entity.getId());
activityDTO.setDescription(entity.getDescription());
activityDTO.setCreatedBy(entity.getCreatedBy());
activityDTO.setCreateTime(entity.getCreateTime());
activityDTO.setUpdatedBy(entity.getUpdatedBy());
activityDTO.setUpdateTime(entity.getUpdateTime());
return activityDTO;
}
}
ActivityController.java
package com.calendar.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.calendar.dto.ActivityDTO;
import com.calendar.service.ActivityService;
#RestController
#RequestMapping("activity")
public class ActivityController {
#Autowired
private ActivityService activityService;
private ActivityService getService() {
System.out.println("service= " + activityService);
return activityService;
}
#Transactional(readOnly = true)
#GetMapping("")
#ResponseBody
public List<ActivityDTO> findAll() {
System.out.println("SIL findAll");
return getService().findAll();
}
}
AppConfig.java
package com.calendar.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan(basePackages = "com.calendar")
public class AppConfig implements WebMvcConfigurer {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//to see html files
configurer.enable();
}
//Entity manager
#Bean(name = "Calendar_PU")
public LocalEntityManagerFactoryBean getEntityManagerFactoryBean() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("Calendar_PU");
return factoryBean;
}
}
Regards,
Francesco
Try adding #EnableJpaRepositories to your AppConfig:
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "com.calendar.repository")
#ComponentScan(basePackages = "com.calendar")
public class AppConfig implements WebMvcConfigurer {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//to see html files
configurer.enable();
}
//Entity manager
#Bean(name = "Calendar_PU")
public LocalEntityManagerFactoryBean getEntityManagerFactoryBean() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("Calendar_PU");
return factoryBean;
}
}
You also need to change your pom.xml. There are too many dependencies (most of them are already part of spring-data-jpa) and spring-data-jpa requires Spring 5.3.5.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.calendar</groupId>
<artifactId>calendar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Calendar</name>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>5.3.5</springframework.version>
<jackson.version>2.11.2</jackson.version>
<email.version>1.6.2</email.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.0</version>
</dependency>
</dependencies>
<repositories>
</repositories>
<build>
<finalName>company-calendar</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
This is why you should consider using Spring Boot. You will avoid issues with dependencies that do not work together.

created repository method is returning wrong output like packagename.classname.table (com.blogconduitapi.entity.Users#6a3258a4)

I am new lerner of spring boot, i am creating a project after inserting user data into database when i am fetching data from table using method "User findByEmail(String email) it should return user object but it returning something like "com.blogconduitapi.entity.Users#5e2f219c".
All the codes are mentioned below
this is entity class
package com.blogconduitapi.entity;
import javax.persistence.*;
#Entity
#Table(name = "users")
public class Users {
#Id
#GeneratedValue
private int id;
private String name;
private String email;
private String password;
private boolean isEnabled;
public Users() {
}
public Users(String name, String email, String password, boolean isEnabled) {
this.name = name;
this.email = email;
this.password = password;
this.isEnabled = isEnabled;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean enabled) {
isEnabled = enabled;
}
}
this is controller
package com.blogconduitapi.controller;
import com.blogconduitapi.entity.Users;
import com.blogconduitapi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class UserController {
#Autowired
UserService userService;
#PostMapping(value = "/register")
public String registerUser(#RequestBody Users users) {
Users existingUsers1 = userService.findUser(users.getEmail());
users.setEnabled(true);
userService.createUser(users);
return "user save successfully";
}
}
this is UserService
package com.blogconduitapi.service;
import com.blogconduitapi.entity.Users;
public interface UserService {
Users findUser(String email);
void createUser(Users users);
}
this is repository
package com.blogconduitapi.repository;
import com.blogconduitapi.entity.Users;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<Users, Integer> {
Users findByEmail(String email);
}
5.this is serviceImpl
package com.blogconduitapi.service.impl;
import com.blogconduitapi.entity.Users;
import com.blogconduitapi.exception.UserDefinedException;
import com.blogconduitapi.repository.UserRepository;
import com.blogconduitapi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UserServiceImpl implements UserService {
#Autowired
UserRepository userRepository;
#Override
public Users findUser(String email) {
Users users = userRepository.findByEmail(email);
System.out.println("{{{{{{{{{}}}}}}}}}}} " + users);
if (users != null) throw new UserDefinedException("mail already exist");
return users;
}
#Override
public void createUser(Users users) {
if (users.getName().isEmpty() || users.getEmail().isEmpty() || users.getPassword().isEmpty()) {
throw new UserDefinedException("There are some required fields are missing");
}
userRepository.save(users);
}
}
application.property
spring.datasource.url= jdbc:postgresql://localhost:5432/apidb
spring.datasource.username=postgres
spring.datasource.password=admin
spring.jpa.hibernate.ddl-auto=update
7.this is pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>blogconduitapi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>blogconduitapi</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jdbc -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The method is working it's just the issue with print. Override toString() method in your User class and try printing the user again. Java has no idea how to convert your User to string and print it in format you would like otherwise.

Consider defining a bean of type 'javax.persistence.EntityManager' in your configuration

I am a beginner to spring. So right now I am starting to learn spring boot and build this simple project, but when I ran it I got this error "
Field entityManager in sagala.rest.boot.remade.dao.EmployeeDaoImpl required a bean of type 'javax.persistence.EntityManager' that could not be found.".
Here is my controller class
package sagala.rest.boot.remade.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sagala.rest.boot.remade.entity.Employee;
import sagala.rest.boot.remade.service.EmployeeService;
#RestController
#RequestMapping("/api")
public class MainController {
#Autowired
private EmployeeService employeeService;
#GetMapping("/employees")
public List<Employee> findAll() {
return employeeService.findAll();
}
}
Here is the Service class
package sagala.rest.boot.remade.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sagala.rest.boot.remade.dao.EmployeeDao;
import sagala.rest.boot.remade.entity.Employee;
#Service
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
private EmployeeDao employeeDao;
#Override
#Transactional
public List<Employee> findAll() {
return employeeDao.findAll();
}
}
Here is the DAO class
package sagala.rest.boot.remade.dao;
import java.util.List;
import javax.persistence.EntityManager;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import sagala.rest.boot.remade.entity.Employee;
#Repository
public class EmployeeDaoImpl implements EmployeeDao {
#Autowired
private EntityManager entityManager;
#Override
public List<Employee> findAll() {
Session session =entityManager.unwrap(Session.class);
Query<Employee> query =session.createQuery("from Employee", Employee.class);
List<Employee> employees =query.getResultList();
return employees;
}
}
Here is the entity class
package sagala.rest.boot.remade.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
public Employee() {
}
public Employee(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Here is the POM file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>sagala</groupId>
<artifactId>rest.boot.remade</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rest.boot.remade</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Here is the application properties
spring.datasource.url=jdbc:mysql://localhost:3306/employee_directory?useSSL=false&serverTimezone=UTC
spring.datasource.username=spring*******
spring.datasource.password=spring*******
If anyone can help me. Thanks
I changed the spring boot version from 2.2.6 to 2.1.13 and everything works fine. Seems like the javax.persistence.EntityManager is corrupt in the newer spring boot version. Eventhough deleted repo multiple times, I still could not find JpaRepository interface when try to extends it as another alternative dao implementation.

Resources