Why my view is not displayed. Spring boot - spring-boot

I am creating a learning project, I can't figure out why my view is not showing on localhost.
I am saving those html files in main\resource\template
but still the html file is not rendered instead a string is showing up on the screen.
My Controllers
package com.blog.test.controllers;
import com.blog.test.entities.Users;
import com.blog.test.repository.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class Home {
#Autowired
UsersRepository usersRepository;
#GetMapping("index")
public String showHome(Model model) {
return "index";
}
#GetMapping("registration")
public String showRegistrationForm(Model model) {
Users users = new Users();
model.addAttribute("users", users);
return "registration";
}
}
my entities
package com.blog.test.entities;
import javax.persistence.*;
import java.time.LocalDateTime;
#Table(name = "POSTS")
#Entity
public class Posts {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int post_id;
#ManyToOne
private Users users;
private LocalDateTime created;
private String Title;
public Posts(){}
public Posts(int post_id, Users users, LocalDateTime created) {
this.post_id = post_id;
this.users = users;
this.created = created;
}
}
and
package com.blog.test.entities;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
#Table(name = "USERSDETAILS")
#Entity
#Getter
#Setter
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int userid;
#OneToOne(mappedBy = "users")
private LoginInfo loginInfo;
#OneToMany(mappedBy = "users")
List<Posts> userPosts;
private String name;
private LocalDateTime created;
public Users(){}
public Users(int userid, LoginInfo loginInfo, String name, LocalDateTime created) {
this.userid= userid;
this.loginInfo = loginInfo;
this.name = name;
this.created = created;
}
}
and
package com.blog.test.entities;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.GeneratorType;
import javax.persistence.*;
#Table(name = "LOGININFODETAILS")
#Entity
#Getter
#Setter
public class LoginInfo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int loginId;
#OneToOne
#JoinColumn
private Users users;
private String username;
private String password;
public LoginInfo(int loginId, String username, String password) {
this.loginId = loginId;
this.username = username;
this.password = password;
}
public LoginInfo() {
}
}
and my pom.xml file is
<?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.blog</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</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>
<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>9.0.44</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</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>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
my html files are
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Welcome</title>
</head>
<body>
<h1>Welcome</h1>
<div>
<a th:href="#{/registration}">Go to Registration Form</a>
</div>
</body>
</html>
BUT nothing is coming up when I hit the localhost:8082\index
where do I get wrong.enter image description here

RestController annotation will return the json response not HTML or JSP.
#RestController = #Controller + #ResponseBody.
#RestController is used to create RESTful web services. For returning html or jsp, annotate the controller class with #Controller annotation.

Use #Controller instead of #RestController
#Controller
public class Home {
#Autowired
UsersRepository usersRepository;
#GetMapping("index")
public String showHome(Model model) {
return "index";
}
#GetMapping("registration")
public String showRegistrationForm(Model model) {
Users users = new Users();
model.addAttribute("users", users);
return "registration";
}
}
Difference between #Controller and #RestController is where we use when we need JSON_RESPONSE which we use in REST API.
and #Controller will return HTML and JS e.g View

Related

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.

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.

MapStruct ignores fields

I'm new to Java Spring Boot. I decided to use MapStruct because it's similar to ASP.NET Core's AutoMapper.
Problem:
The image is pretty self explanatory. It doesn't map firstName and lastName. I thought it could be the underscore e.g. first_name, but then I added password to the DTO model and it's not being set too.
By the way, I tested it by removing the DTO model with the following code and it worked which means that the cause is that UserMapper.
#GetMapping
public ResponseEntity<List<User>> getAll() {
return ResponseEntity.ok(userService.getAll());
}
Log from ReportingPolicy.WARN
2019-10-27 15:58:44.024 DEBUG 24284 --- [nio-5000-exec-1] org.hibernate.SQL : select user0_.id as id1_2_, user0_.email as email2_2_, user0_.first_name as first_na3_2_, user0_.last_name as last_nam4_2_, user0_.password as password5_2_ from users user0_
2019-10-27 15:58:44.033 DEBUG 24284 --- [nio-5000-exec-1] org.hibernate.SQL : select roles0_.user_id as user_id1_1_0_, roles0_.role_id as role_id2_1_0_, role1_.id as id1_0_1_, role1_.description as descr
UserMapper.java
package com.holding.server.mappers;
import java.util.List;
import com.holding.server.dto.UserDTO;
import com.holding.server.entities.User;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
#Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.WARN)
public interface UserMapper {
UserDTO toUserDTO(User user);
List<UserDTO> toUserDTOs(List<User> users);
User toUser(UserDTO userDTO);
}
User.java
package com.holding.server.entities;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Entity(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique = true)
#NotNull
#Size(max = 40)
#Email
private String email;
#NotNull
private String password;
#NotNull
#Size(max = 40)
private String firstName;
#NotNull
#Size(max = 40)
private String lastName;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles;
}
UserDTO.java
package com.holding.server.dto;
import lombok.Data;
#Data
public class UserDTO {
private String email;
private String firstName;
private String lastName;
}
UserServiceImpl.java
package com.holding.server.services;
import java.util.List;
import java.util.Optional;
import com.holding.server.entities.User;
import com.holding.server.repositories.UserRepository;
import com.holding.server.services.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import lombok.AllArgsConstructor;
#AllArgsConstructor
#Service
public class UserServiceImpl implements UserService {
private UserRepository userRepository;
private BCryptPasswordEncoder bCryptPasswordEncoder;
#Override
public List<User> getAll() {
return userRepository.findAll();
}
#Override
public Optional<User> get(Long id) {
return userRepository.findById(id);
}
#Override
public Optional<User> create(User user) {
if (userRepository.findByEmail(user.getEmail()).isPresent()) {
return Optional.empty();
}
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
return Optional.ofNullable(userRepository.save(user));
}
#Override
public Optional<User> update(User user) {
Optional<User> userToUpdate = get(user.getId());
if (userToUpdate.isPresent()) {
userToUpdate.get().setFirstName(user.getFirstName());
userToUpdate.get().setLastName(user.getLastName());
userToUpdate.get().setRoles(user.getRoles());
if (user.getPassword() != null) {
userToUpdate.get().setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
}
return Optional.ofNullable(userRepository.save(userToUpdate.get()));
}
return Optional.empty();
}
#Override
public void delete(Long id) {
Optional<User> user = get(id);
if (user.isPresent()) {
userRepository.delete(user.get());
}
}
}
UserController.java
package com.holding.server.controllers;
import java.util.List;
import java.util.Optional;
import com.holding.server.dto.UserDTO;
import com.holding.server.entities.User;
import com.holding.server.mappers.UserMapper;
import com.holding.server.services.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.AllArgsConstructor;
#AllArgsConstructor
#RestController
#RequestMapping("/api/users")
public class UserController {
private UserService userService;
private UserMapper userMapper;
#GetMapping
public ResponseEntity<List<UserDTO>> getAll() {
return ResponseEntity.ok(userMapper.toUserDTOs(userService.getAll()));
}
#GetMapping("/{id}")
public ResponseEntity<UserDTO> get(#PathVariable("id") Long id) {
Optional<User> user = userService.get(id);
if (user.isPresent()) {
return ResponseEntity.ok(userMapper.toUserDTO(user.get()));
}
return ResponseEntity.notFound().build();
}
#PostMapping
public ResponseEntity<UserDTO> create(#RequestBody UserDTO userDTO) {
User user = userMapper.toUser(userDTO);
user.setId(null);
Optional<User> savedUser = userService.create(user);
if (savedUser.isPresent()) {
return ResponseEntity.ok(userMapper.toUserDTO(savedUser.get()));
}
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
#PutMapping("/{id}")
public ResponseEntity<UserDTO> update(#PathVariable(required = true) Long id, #RequestBody UserDTO userDTO) {
User user = userMapper.toUser(userDTO);
user.setId(id);
Optional<User> updatedUser = userService.update(user);
if (updatedUser.isPresent()) {
return ResponseEntity.ok(userMapper.toUserDTO(updatedUser.get()));
}
return ResponseEntity.badRequest().build();
}
#DeleteMapping("/{id}")
public ResponseEntity<Void> delete(#PathVariable(required = true) Long id) {
if (userService.get(id).isPresent()) {
userService.delete(id);
return ResponseEntity.ok().build();
}
return ResponseEntity.notFound().build();
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<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.0.RELEASE</version>
<relativePath />
</parent>
<groupId>com.holding</groupId>
<artifactId>server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<org.mapstruct.version>1.3.1.Final</org.mapstruct.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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.10.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
If you need something else, ask me.
MapStruct creates generated class at compile time. You might want to clean and rebuild then check if the generated Mapper contains the required mappings.

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

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).

Resources