No bean named 'mongoTemplate' available - java

I am new to springboot and mongodb and cannot find the solution for my problem. Any help would be much appreciated. Thank you.
I am seeing this warning:
WARN 4960 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository' defined in com.example.login.User.UserRepository defined in #EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available
and error:
ERROR 4960 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean named 'mongoTemplate' that could not be found.
Action:
Consider defining a bean named 'mongoTemplate' in your configuration.
Here is my User.java
package com.example.login.User;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "users")
public class User {
#Id
private String id;
// id is autogenerated
private String email;
private String firstName;
private String lastName;
private String password;
public User(String email, String firstName, String lastName, String password) {
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "User [email=" + email + ", firstName=" + firstName + ", lastName=" + lastName + ", password=" + password
+ "]";
}
}
UserController.java
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class UserController {
// #Autowired
// public UserController(UserService userService) {
// this.userService = userService;
// }
private UserRepository userRepository;
#PostMapping("/addUser")
public String addUser(#RequestBody User user) {
userRepository.save(user);
return "added user with id: " + user.getId();
}
#GetMapping("/getAllUsers")
public List<User> getAllUsers() {
return userRepository.findAll();
}
#GetMapping("/getAllUsers/{id}")
public Optional<User> getUser(#PathVariable String id) {
return userRepository.findById(id);
}
#DeleteMapping("/removeUser")
public String deleteUser(#PathVariable String id) {
userRepository.deleteById(id);
return "removed user with id" + id;
}
}
UserRepository.java
package com.example.login.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends MongoRepository<User, String>{
}
LoginApplication.java
package com.example.login;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
#SpringBootApplication
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,WebMvcAutoConfiguration.class,MongoAutoConfiguration.class})
public class LoginApplication {
public static void main(String[] args) {
SpringApplication.run(LoginApplication.class, args);
}
}
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.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>login</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>login</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-rest</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-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</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>

Related

Getting an error while using String type as primary key. Error creating bean with name 'entityManagerFactory'

Error creating bean with name 'entityManagerFactory' defined in class
path resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]:
Invocation of init method failed; nested exception is
org.hibernate.AnnotationException: No identifier specified for entity:
com.hashir.smartcity.entities.User
I am using a String type field as my primary key. Here is my Entity package:
User.java:
package com.hashir.smartcity.entities;
import javax.persistence.Entity;
#Entity
public class User extends AbstractEntity{
private String firstName;
private String lastName;
private String email;
private String password;
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;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Wander.java:
package com.hashir.smartcity.entities;
import javax.persistence.Entity;
#Entity
public class Wander extends AbstractEntity{
private String placesToEat;
private String visit;
private String metro;
public String getPlacesToEat() {
return placesToEat;
}
public void setPlacesToEat(String placesToEat) {
this.placesToEat = placesToEat;
}
public String getVisit() {
return visit;
}
public void setVisit(String visit) {
this.visit = visit;
}
public String getMetro() {
return metro;
}
public void setMetro(String metro) {
this.metro = metro;
}
}
AbstractEntity.java:
package com.hashir.smartcity.entities;
import javax.persistence.Id;
public class AbstractEntity {
#Id
private String location;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
I want to register a user, provide a login and want my controller class to display menu as soon as the user enters location.
Below is my Controller class:
UserController.java:
package com.hashir.smartcity.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.hashir.smartcity.entities.User;
import com.hashir.smartcity.repos.UserRepository;
#Controller
public class UserController {
#Autowired
UserRepository userRepository;
#RequestMapping("/showReg")
public String showRegistrationPage() {
return "login/registerUser";
}
#RequestMapping(value="/registerUser",method=RequestMethod.POST)
public String register(#ModelAttribute("user")User user) {
userRepository.save(user);
return "login/login";
}
#RequestMapping(value="/login",method=RequestMethod.POST)
public String login(#RequestParam("email")String email,#RequestParam("password")String password,ModelMap modelMap) {
User user = userRepository.findByEmail(email);
if(user.getPassword().equals(password)) {
return "/enterLocation";
}
else {
modelMap.addAttribute("msg", "Incorrect user name or Password. Please try again.");
}
return "login/login";
}
#RequestMapping(value="/enterLocation",method=RequestMethod.POST)
public String enterLocation(#RequestParam("location")String location) {
return "displayMenu";
}
}
enterLocation.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Enter Location</title>
</head>
<body>
<h2>Enter Location</h2>
<form action="enterLocation" method="post">
Enter Location:<input type="text" name="location"/>
<input type="submit" value="search"/>
</form>
</body>
</html>
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.5.5</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.hashir.smartcity</groupId>
<artifactId>smartcity</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>smartcity</name>
<description>Smart City App</description>
<properties>
<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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</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>
P.S. I am just a beginner.
Using MappedSuperclass
#MappedSuperclass
public abstract class AbstractEntity {
// common mappings
#Id
private String location;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
#Entity
#Table(name = "UserTable")
public class User extends AbstractEntity {
// other mappings
}
#Entity
#Table(name = "WanderTable")
public class WanderTableObject extends AbstractEntity {
// other mappings
}
As Navnath already mentioned the #Entity annotation expects an #Id notation on one of the members inside the class.
With what you are trying to do, using an abstract entity class to extend in all your entities, you can add the #Entity annotation on the abstract class.

Spring Boot Whitelabel Error page (type=Internal Server Error, status=500)

I am trying to follow the online tutorial of spring boot and all of my java file seem ok. Here they are :
User.java file
package net.javaguides.springboot.model;
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 = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
private String email;
public User(String firstName, String lastName, String email) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long 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;
}}
UserRepository.java file
package net.javaguides.springboot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.javaguides.springboot.model.User;
#Repository
public interface UserRepository extends JpaRepository<User, Long>{
}
UserController.java file
package net.javaguides.springboot.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 net.javaguides.springboot.model.User;
import net.javaguides.springboot.repository.UserRepository;
#RestController
#RequestMapping("api/")
public class UserController {
#Autowired
private UserRepository userRepository;
#GetMapping("users")
public List<User> getUsers() {
return this.userRepository.findAll();
}}
And the last one is the file named Thinghiem1Application.java
package net.javaguides.springboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import net.javaguides.springboot.model.User;
import net.javaguides.springboot.repository.UserRepository;
#SpringBootApplication
public class Thinghiem1Application implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(Thinghiem1Application.class, args);
}
#Autowired
private UserRepository userRepository;
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
this.userRepository.save(new User("Duc", "Nguyen", "ramesh#gmail.com"));
this.userRepository.save(new User("Long", "Hoang", "tom#gmail.com"));
this.userRepository.save(new User("Tony", "Lan", "dir#gmail.com"));
}}
Sorry for my mistake, here is my thinghiem1/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.5.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>net.javaguides</groupId>
<artifactId>thinghiem1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>thinghiem1</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-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</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>
As you can see, there was no error.
But when I ran the Thinghiem1Application.java file as Spring Boot App, it said to me that there was an error like this 2021-07-15 20:28:27.457 ERROR 11092 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: No default constructor for entity: : net.javaguides.springboot.model.User; nested exception is org.hibernate.InstantiationException: No default constructor for entity: : net.javaguides.springboot.model.User] with root cause
and the page can not load, it said to me that Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.
I am very confusing with this problem and trying to fix it but still can not fix it, could you please give me some ideas ? Thank you in advance.
You need to have a default constructor such as:
public User() {
}
Hibernate uses the default constructor to create entity objects. If the default constructor is not available in any of the entities, InstantiationException: There was an unexpected error (type=Internal Server Error, status=500). will be thrown from hibernate.
add default constructor in your user entity class
You just need to add an empty constructor to User class:
public User() {
}
All persistent classes must have a default constructor so that Hibernate can instantiate them using Constructor.newInstance(). It is recommended that you have a default constructor with at least package visibility for runtime proxy generation in Hibernate. so you must add a default constructor.
public User() {
}
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback. You will find more information here or here.
The whole log should be something like:
Tue Sep 27 17:27:29 WIB 2022
There was an unexpected error (type=Internal Server Error, status=500).
No message available

Field topicRepository in api.dataBase.basic.apiDatabase.Models.TopicService required a bean of type

I am in the process of learning Java spring Boot from the tutorial found here
I keep getting the "Field topicRepository in api.dataBase.basic.apiDatabase.Models.TopicService required a bean of type 'api.dataBase.basic.apiDatabase.Interface.TopicRepository' that could not be found."
I read that this error can occur because of componentScan is failing for poor annotation of the class or poor package layout.
Layout of my java packages
lay out of my project
My classes are the following;
package api.dataBase.basic.apiDatabase;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication ()
public class ApiDatabaseApplication {
public static void main(String[] args) {
SpringApplication.run(ApiDatabaseApplication.class, args);
}
}
Topic.java
package api.dataBase.basic.apiDatabase.Models;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Topic {
#Id
private String id;
private String name;
private String description;
//private Address address;
public Topic(final String id, final String name, final String description) {
this.id = id;
this.name = name;
this.description = description;
}
public Topic() {
}
#Id
public String getId() {
return id;
}
public void setId(final String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
}
TopicRepository.java
package api.dataBase.basic.apiDatabase.Interface;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import api.dataBase.basic.apiDatabase.Models.Topic;
#Repository
public interface TopicRepository extends CrudRepository <Topic, String>{
}
TopicService.java
package api.dataBase.basic.apiDatabase.Models;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import api.dataBase.basic.apiDatabase.Interface.TopicRepository;
#Service
public class TopicService {
#Autowired
private TopicRepository topicRepository;
private List<Topic> Oldtopics = new ArrayList<>(Arrays.asList(
new Topic("1001", "test", "hello 1"),
new Topic("1002", "hello", "hello 2")
));
public List<Topic> getTopics() {
List<Topic> topics = new ArrayList<>();
topicRepository.findAll().forEach(topics::add);
return topics;
}
public Topic getTopic(String id) {
return Oldtopics.stream().filter(t -> t.getId().equals(id)).findFirst().get();
}
public void addTopic(final Topic topic) {
topicRepository.save(topic);
}
public void updateTopic(final Topic topic, final String id) {
for (int i = 0; i < Oldtopics.size(); i++) {
if (Oldtopics.get(i).getId().equals(id)) {
Oldtopics.set(i, topic);
return;
}
}
}
public void deleteTopic(String id) {
Oldtopics.removeIf(t -> t.getId().equals(id));
}
public void deleteTopic(final String[] id) {
for (int i = 0; i < Oldtopics.size(); i++) {
for (String ids : id) {
if (Oldtopics.get(i).getId().equals(ids)) {
Oldtopics.remove(i);
}
}
}
}
}
Any help will be appreciated.
Full Stack Trace.
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-11-21 19:18:05.350 ERROR 4192 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field topicRepository in api.dataBase.basic.apiDatabase.Models.TopicService required a bean of type 'api.dataBase.basic.apiDatabase.Interface.TopicRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'api.dataBase.basic.apiDatabase.Interface.TopicRepository' in your configuration.
POM:
<?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.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>api.dataBase.basic</groupId>
<artifactId>apiDatabase</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apiDatabase</name>
<description>API project with JPA database</description>
<properties>
<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.apache.derby</groupId>
<artifactId>derby</artifactId>
</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>
This can be the case for missed configuration and thus messed component scan.
I'd suggest that you should add 'Config.java' with following content to your source root (src/main/java)
#Configuration
#EnableJpaRepositories
class Config {
}

no natively generated identity value

i am new to springframework technology and i am struggling to solve the following error.
the project starts successfully, i get the following error when the postman is executed
can anyone hel me solving the issue.
i guess i have pasted the important classes, i can post the whole code if needed
usercontroller
package com.appsdeveloper.blog.app.ws.controller;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
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 com.appsdeveloper.blog.app.ws.service.UserService;
import com.appsdeveloper.blog.app.ws.shared.dto.UserDto;
import com.appsdeveloper.blog.app.ws.ui.model.request.UserDetailsRequestModel;
import com.appsdeveloper.blog.app.ws.ui.model.response.UserRest;
#RestController
#RequestMapping("users")//http://localhost:8586/users
public class UserController{
#Autowired(required=true)//the bracket added from the internet
UserService userService;
//#Autowired
//private UserRepository userRepository;
#PostMapping
public UserRest createUser(#RequestBody UserDetailsRequestModel userDetails){
UserRest returnValue = new UserRest();
UserDto userDto = new UserDto();
BeanUtils.copyProperties(userDetails, userDto);
UserDto createdUser = userService.createUser(userDto);
BeanUtils.copyProperties(createdUser, returnValue);
return returnValue;
}
#DeleteMapping
public String deleteUser(){
return "delete user was called";
}
#GetMapping
public String getUser(){
return "get User was called";
}
#PutMapping
public String updateUser(){
return "update user was called";
}
}
UserEntity
package com.appsdeveloper.blog.app.ws.io.entity;
import java.io.Serializable;
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="users", schema = "photo_app" )//name of table created to store information
public class UserEntity implements Serializable {
private static final long serialVersionUID = 7401188933477397731L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="Id")
private long id;
#Column(name= "userId", nullable = false)
private String userId;
#Column(name = "firstName", nullable = false, length = 50)//the length is important to avoid default size 0f 250 varchar
private String firstName;
#Column(name = "lastName", nullable = false, length = 50)
private String lastname;
#Column(name = "email", length = 50)
private String email;
#Column(name = "password", nullable = false)
private String encryptedPassword;
//#Column(name = "emailVerificationToken", nullable = false)
private String emailVerificationToken;
#Column(name = "emailVerificationStatus", nullable=false)
private Boolean emailVerificationStatus = false;
public long getId() {
return id;
}
public String getUserId() {
return userId;
}
public String getFirstName() {
return firstName;
}
public String getLastname() {
return lastname;
}
public String getEmail() {
return email;
}
public String getEncryptedPassword() {
return encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
///////////////////////////////////////////
public void setId(long id) {
this.id = id;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setEmail(String email) {
this.email = email;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public void setEmailVerificationStatus(boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
application.property
spring.datasource.username=root
spring.datasource.password=
spring.datasource.url=jdbc:mysql://localhost:3306/photo_app
server.port=8586
spring.jpa.hibernate.use-new-id-generator-mappings=false
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.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.appsdeveloperblog-app-ws</groupId>
<artifactId>mobile-app-ws</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mobile-app-ws</name>
<description>Demo project for Spring Boot</description>
<properties><!--</tiles:insertDefinition>-->
<!-- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>-->
<java.version>1.8</java.version>
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</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-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.0.Alpha4</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jadira.usertype/usertype.core -->
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>7.0.0.CR1</version>
</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>
error code
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: The database returned no natively generated identity value; nested exception is org.hibernate.HibernateException: The database returned no natively generated identity value] with root cause
org.hibernate.HibernateException: The database returned no natively generated identity value
You have to auto-increment your id column in your database.
Something like this: id INT NOT NULL AUTO_INCREMENT

HsqlDB with spring-boot-starter-parent 1.4.0.RELEASE

This the pom.xml for maven build project that I am using to resolve dependencies.
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.raj</groupId>
<artifactId>hSQLdb1</artifactId>
<version>0.1.0</version>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</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>
<executions>
<execution>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Below are the properties file for my sample application here I am using applicationproperties and application-hsqldb.properties
application.properties
spring.profiles.active=hsqldb
# Hibernate
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.jadira.usertype.autoRegisterUserTypes=true
**application-hsqldb.properties**
# Hibernate
spring.jpa.hibernate.ddl-auto=validate
# Initialization
spring.datasource.schema=classpath:/data/hsqldb/schema.sql
spring.datasource.data=classpath:/data/hsqldb/data.sql
data.sql
INSERT INTO EMP(f_name, l_name) VALUES('Rajendar','Kumar');
INSERT INTO EMP(f_name, l_name) VALUES('Ramesh','Kumar');
schema.sql
DROP TABLE EMP IF EXISTS;
CREATE TABLE emp (
id BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL,
f_name VARCHAR(100) NOT NULL,
l_name VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
);
Below is the controller for my rest services that have two service for greeting and read data from database
import com.raj.hSQLdb.pojo.Employee;
import com.raj.hSQLdb.pojo.Greating;
import com.raj.hSQLdb.service.impl.ProcessEmpDataService;
#RestController
#RequestMapping("/app")
public class Controller{
#Autowired
private ProcessEmpDataService empDataService;
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#GetMapping("/greeting")
public String sayHello(#RequestParam(value="name", defaultValue="Rajendar") String name) {
return new Greating(String.valueOf(counter.incrementAndGet()), String.format(template, name)).toString();
}
#RequestMapping(value = {"/read"}, method = RequestMethod.GET)
public ResponseEntity<?> read(Long id) {
Employee response = empDataService.findOne(id);
return new ResponseEntity<Employee>(response,HttpStatus.OK);
}
}
Entity
package com.raj.hSQLdb.pojo;
import java.io.Serializable;
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="emp")
public class Employee implements Serializable{
private static final long serialVersionUID = 5667869092245806231L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name = "f_name")
private String firstName;
#Column(name = "l_name")
private String lastName;
public Long getId() {
return id;
}
public void setId(Long 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;
}
#Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
** Greating **
package com.raj.hSQLdb.pojo;
public class Greating{
public Greating(String code, String message) {
this.code=code;
this.message=message;
}
protected String code;
private String message;
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
}
Repository
package com.raj.hSQLdb.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.raj.hSQLdb.pojo.Employee;
#Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
Service
package com.raj.hSQLdb.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.raj.hSQLdb.pojo.Employee;
import com.raj.hSQLdb.repository.EmployeeRepository;
#Component
public class ProcessEmpDataService {
#Autowired
private EmployeeRepository repository;
public Employee findOne(Long id) {
Employee emp = repository.findOne(id);
return emp;
}
}
main class to run the application
package com.raj.hSQLdb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#SpringBootApplication
#EnableTransactionManagement
public class ServletInitializer {
/**
* #param args
*/
public static void main(String[] args) {
SpringApplication.run(ServletInitializer.class, args);
}
}

Categories