package com.loginregister.loginregister.entities;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Role {
#Id
private String name;
#ManyToMany(mappedBy = "roles")
private List<User> users;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public Role(String name, List<User> users) {
this.name = name;
this.users = users;
}
public Role() {
}
public Role(String name) {
this.name = name;
}
}
Role.java
package com.loginregister.loginregister.entities;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import javax.persistence.GeneratedValue;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Task {
#Id
#GeneratedValue
private Long id;
#NotEmpty
private String date;
#NotEmpty
private String startTime;
#NotEmpty
private String stopTime;
#NotEmpty
private String Description;
#ManyToOne
#JoinColumn(name = "USER_EMAIL")
private User user;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getStopTime() {
return stopTime;
}
public void setStopTime(String stopTime) {
this.stopTime = stopTime;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Task(String date, String startTime, String stopTime, String description, User user) {
this.date = date;
this.startTime = startTime;
this.stopTime = stopTime;
Description = description;
this.user = user;
}
public Task(String date, String startTime, String stopTime, String description) {
this.date = date;
this.startTime = startTime;
this.stopTime = stopTime;
Description = description;
}
public Task() {
}
}
Task.java
package com.loginregister.loginregister.entities;
import org.springframework.scheduling.config.Task;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import java.util.List;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
#Entity
public class User {
#Id
#Email
#NotEmpty
#Column(unique = true)
private String email;
#NotEmpty
private String name;
#Size(min = 4)
private String password;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Task> tasks;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "USER_ROLES",joinColumns = {
#JoinColumn(name = "USER_EMAIL", referencedColumnName = "email")
},inverseJoinColumns = {#JoinColumn(name = "ROLE_NAME", referencedColumnName = "name")})
private List<Role> roles;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public User(String email, String name, String password) {
this.email = email;
this.name = name;
this.password = password;
}
public User() {
}
}
User.java
package com.loginregister.loginregister.repositories;
import com.loginregister.loginregister.entities.Role;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role, String>{
}
RoleRepository.java
package com.loginregister.loginregister.repositories;
import com.loginregister.loginregister.entities.Task;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TaskRepository extends JpaRepository<Task, Long> {
}
TaskRepository.java
package com.loginregister.loginregister.repositories;
import com.loginregister.loginregister.entities.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, String> {
}
UserRepository
package com.loginregister.loginregister;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class LoginRegisterApplication {
public static void main(String[] args) {
SpringApplication.run(LoginRegisterApplication.class, args);
}
}
LoginRegisterApplication.java
spring.datasource.url=jdbc:mysql://localhost:3306/SpringAuth?useSSL=false
spring.datasource.username=root
spring.datasource.password=****
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
application.properties
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.LoginRegister</groupId>
<artifactId>login-register</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>login-register</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</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>
</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>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.7.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
pom.xml
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.941 s <<< FAILURE! - in com.loginregister.loginregister.LoginRegisterApplicationTests
[ERROR] contextLoads(com.loginregister.loginregister.LoginRegisterApplicationTests) Time elapsed: 0.005 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: 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: #OneToOne or #ManyToOne on com.loginregister.loginregister.entities.Task.user references an unknown entity: com.loginregister.loginregister.entities.User
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on com.loginregister.loginregister.entities.Task.user references an unknown entity: com.loginregister.loginregister.entities.User
This can be resolved by :
Hibernate jpa 2.1 jar which is a part of spring-boot-started-data-jpa. Remove dependencies in .m2 folder and again report pom.xml
OR<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Add Repository Annotation
Related
I'm fairly new at maven spring boot.
I'm running mvn clean install then mvn spring-boot:run
I'm then able to go an http post and insert data into the database. I can do an http get and see the data. I can view the data in mysql.
When I re-compile and run mvn clean install again, I'm not sure what's making it delete all the data in my product table in the database.
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.0</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<groupId>sample.info</groupId>
<artifactId>mainapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mainapp</name>
<description>Spring Boot Project</description>
<properties>
<java.version>18</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-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</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>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkCount>0</forkCount>
<reuseForks>true</reuseForks>
<argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.properties
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/appdb
spring.datasource.username=root
spring.datasource.password=
server.port = 9095
MainappApplication.java
package sample.info.mainapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
#EnableJpaAuditing
#SpringBootApplication
public class MainappApplication {
public static void main(String[] args) {
SpringApplication.run(MainappApplication.class, args);
}
}
controllers/ProductController.java
package sample.info.mainapp.controllers;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
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 sample.info.mainapp.model.Product;
import sample.info.mainapp.repository.ProductRepository;
#RestController
#RequestMapping("/api")
public class ProductController {
#Autowired
ProductRepository productRepository;
#GetMapping("/products")
public List<Product> getAllProducts() {
final List<Product> productList = new ArrayList<Product>();
Iterable<Product> iterable = productRepository.findAll();
iterable.forEach(productList::add);
return productList;
}
#GetMapping("/products/{id}")
public ResponseEntity<Product> getProductById(#PathVariable(value = "id") Long id) {
Optional<Product> product = productRepository.findById(id);
return product.isPresent() ? new ResponseEntity<Product>(product.get(), HttpStatus.OK)
: new ResponseEntity("No data found", HttpStatus.NOT_FOUND);
}
#PostMapping("/products")
public Product createProduct(#RequestBody Product product) {
return productRepository.save(product);
}
#PutMapping("/products/{id}")
public ResponseEntity<Product> updateProduct(#PathVariable(value = "id") Long id, #RequestBody Product newProduct) {
Optional<Product> product = productRepository.findById(id);
if (product.isPresent()) {
Product prod = product.get();
prod.setDescription(newProduct.getDescription());
prod.setPrice(newProduct.getPrice());
prod.setTitle(newProduct.getTitle());
prod = productRepository.save(prod);
return ResponseEntity.ok().body(prod);
} else {
return ResponseEntity.notFound().build();
}
}
#DeleteMapping("/products/{id}")
public ResponseEntity<Product> deleteProduct(#PathVariable(value = "id") Long id) {
Optional<Product> product = productRepository.findById(id);
if (product.isPresent()) {
productRepository.delete(product.get());
return new ResponseEntity("Product has been deleted successfully.", HttpStatus.OK);
} else {
return ResponseEntity.notFound().build();
}
}
}
model/Product.java
package sample.info.mainapp.model;
import javax.persistence.*;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.Date;
#Entity
#Table(name = "products")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = { "created_at", "updated_at" }, allowGetters = true)
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "title")
private String title;
#Column(name = "description")
private String description;
#Column(name = "price")
private float price;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date created_at;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updated_at;
public Product() {
}
public Product(Long id, String title, String description, float price) {
this.id = id;
this.title = title;
this.description = description;
this.price = price;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Date getCreated_at() {
return created_at;
}
public Date getUpdated_at() {
return updated_at;
}
}
repository/ProductRepository.java
package sample.info.mainapp.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import sample.info.mainapp.model.Product;
#Repository
public interface ProductRepository extends CrudRepository <Product, Long> {
}
spring.jpa.hibernate.ddl-auto = create -– Hibernate first drops existing tables, then creates new tables. Click here for more details.
Remove / comment this property from application.properties and try.
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
How I "solved" it:
The initial problem was that I forgot to change the package name in the main class that launches the application:
#EnableJpaRepositories(basePackages = {"com.sda.VictorLiviu.ecommerce.jparepository"})
After that I just instanced itemMapper as a normal class in ItemService like this:
ItemMapper itemMapper = new ItemMapper();
and than used its toEntity method as:
itemMapper.toEntity();
. . . . . . . . . . . .
My Spring Boot app says it doesn't have a Bean class which it clearly has. I will post the Pom, service and repository. I want to point out that I have exactly the same class and repository for UserService and OrderService and they don't give any error, the only difference is the #Transactional and I removed it and got the same error.Any suggestions are welcomed!
The Error:
Description:
Field repository in com.sda.VictorLiviu.ecommerce.service.ItemService required a bean of type 'com.sda.VictorLiviu.ecommerce.JpaRepository.ItemRepository' 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 'com.sda.VictorLiviu.ecommerce.JpaRepository.ItemRepository' in your configuration.
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sda.VictorLiviu</groupId>
<artifactId>e-commerce</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>e-commerce</name>
<description>E-commerce website Final Project sda</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>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</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>
ItemService class
package com.sda.VictorLiviu.ecommerce.service;
import com.sda.VictorLiviu.ecommerce.DtoMapper.ItemMapper;
import com.sda.VictorLiviu.ecommerce.JpaRepository.ItemRepository;
import com.sda.VictorLiviu.ecommerce.exceptions.ItemNotFoundException;
import com.sda.VictorLiviu.ecommerce.model.Item;
import com.sda.VictorLiviu.ecommerce.dto.ItemDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
#Transactional
#Service
public class ItemService {
#Autowired
ItemRepository repository;
#Autowired
ItemMapper itemMapper;
public void add(ItemDto dto) {
repository.save(itemMapper.toEntity(dto));
}
public Item delete(Long id) {
repository.deleteById(id);
return null;
}
public List<Item> getItems() {
return repository.findAll();
}
public Item getItemById(Long id) {
Optional<Item> optionalItem = repository.findById(id);
return optionalItem.orElseThrow( () -> new ItemNotFoundException("Couldn't find the specific item!"));
}
}
Repository
package com.sda.VictorLiviu.ecommerce.JpaRepository;
import com.sda.VictorLiviu.ecommerce.model.Item;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface ItemRepository extends JpaRepository<Item, Long> {
}
Item Class
package com.sda.VictorLiviu.ecommerce.model;
import javax.persistence.*;
#Entity
#Table(name="item")
public class Item {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "item_seq_gen")
#SequenceGenerator(name = "item_seq_gen", sequenceName = "item_seq", allocationSize = 1)
#Column(name = "id")
private Long id;
#Column(name = "price")
private double price;
#Column(name = "name")
private String name;
#Column(name = "category")
private String category;
#Column(name = "quantity")
private int quantity;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
ItemDto Class
package com.sda.VictorLiviu.ecommerce.dto;
public class ItemDto {
private Long id;
private double price;
private String name;
private String category;
private int quantity;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
Application.properties
logging.level.org.springframework=info
jwt.signing.key.secret=mySecret
jwt.get.token.uri=/authenticate
jwt.refresh.token.uri=/refresh
jwt.http.request.header=Authorization
jwt.token.expiration.in.seconds=604800
spring.jpa..show-sql=true
spring.h2.console.enabled=true
!!!!!!
Image with my packages
You need to turn on jpa repositories processing.
To do this, annotate your application with #EnableJpaRepositories
I am new in hibernate and don't know am I correct while writing objects.
I want a relationship which is bidirectional for users and roles.
While getting user from controller I am not getting correct object.
User has multiple roles and role has a user. My objects are:
package com.dineshonjava.sdjpa.models;
import java.io.Serializable;
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.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "roles")
public class UserRole implements Serializable{
/**
*
*/
private static final long serialVersionUID = 4515711679485233980L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_role_id",
unique = true)
private Integer userRoleId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinTable(name="user_roles",
joinColumns={#JoinColumn(name="user_role_id")},
inverseJoinColumns={#JoinColumn(name="username")})
private User user;
#Column(name = "role", length = 45)
private String role;
/**
* #param role
*/
public UserRole() {
}
/**
* #param userRoleId
* #param role
*/
public UserRole(String role) {
this.role = role;
}
public UserRole(User user, String role) {
this.user = user;
this.role = role;
}
public Integer getUserRoleId() {
return this.userRoleId;
}
public void setUserRoleId(Integer userRoleId) {
this.userRoleId = userRoleId;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public String getRole() {
return this.role;
}
public void setRole(String role) {
this.role = role;
}
}
And user is:
package com.dineshonjava.sdjpa.models;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "USERS")
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = -7500832548478837146L;
#Id
#Column(name = "username", unique = true,
length = 45)
private String username;
#Column(name = "password",
length = 60)
private String password;
#Column(name = "enabled", nullable = false)
private boolean enabled;
// #OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
#OneToMany(fetch = FetchType.LAZY)
#JoinTable(name="user_roles",
joinColumns={#JoinColumn(name="username")},
inverseJoinColumns={#JoinColumn(name="user_role_id")})
private Set<UserRole> userRole = new HashSet<UserRole>(0);
public User() {
}
public User(String username, String password, boolean enabled) {
this.username = username;
this.password = password;
this.enabled = enabled;
}
public User(String username, String password,
boolean enabled, Set<UserRole> userRole) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.userRole = userRole;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Set<UserRole> getUserRole() {
return this.userRole;
}
public void setUserRole(Set<UserRole> userRole) {
this.userRole = userRole;
}
}
Saving object like:
UserRole role = new UserRole("ROLE_ADMIN");
roleDAO.save(role);
User user = new User("username", "password", true, new HashSet<UserRole>(Arrays.asList(role)));
userDAO.save(user);
Service is:
#Service
public class UserServiceImpl extends HibernateSessionFactroyBase implements UserService{
public void save(User user){
getSession().save(user);
}
#Override
public User find(String username) {
return getSession().get(User.class, username);
}
}
Session factory:
#Transactional
public class HibernateSessionFactroyBase {
#Autowired
SessionFactory sessionFactory;
public Session getSession() {
return sessionFactory.getCurrentSession();
}
}
Application class is:
#SpringBootApplication
public class SpringBootJpaSpringDataApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootJpaSpringDataApplication.class, args);
}
#Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
return new HibernateJpaSessionFactoryBean();
}
}
Controller is:
#RequestMapping(value = "/user", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public User get(#RequestParam(name = "id") String id) {
User user = userRepository.find(id);
return user;
}
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.dineshonjava.sdjpa</groupId>
<artifactId>SpringBootJPASpringData</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBootJPASpringData</name>
<description>SpringBootJPASpringData project for Spring Boot with Spring Data JPA implementation</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.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>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</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>
Property file:
# DataSource settings: set here your own configurations for the database
# connection. In this example we have "dojsb" as database name and
# "root" as username and password.
spring.datasource.url = jdbc:mysql://localhost:3306/product
spring.datasource.username = root
spring.datasource.password = root
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = create
# Naming strategy
#spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
I'm using:
GlassFish 4.1
Hibernate (see pom.xml)
Java EE 7
Eclipse Luna
I don't know why GlassFish can't inject an EntityManager. If i get the EntityManager from EntityManagerFactory, i don't have problems:
protected EntityManager em = Persistence.createEntityManagerFactory("CustomersPU").createEntityManager();
In other hand, if i try to say that GlassFish inject it, get an Exception.:
#PersistenceContext(unitName="CustomersPU")
protected EntityManager em;
pom.xml
<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>me.localtest</groupId>
<artifactId>customersapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven_compiler_source>1.8</maven_compiler_source>
<maven_compiler_target>1.8</maven_compiler_target>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
GenericService
package me.localtest.customersapp.services;
import java.io.Serializable;
import java.util.List;
public interface GenericService<T, PK extends Serializable> {
public T save(T t) throws Throwable;
public T update(T t) throws Throwable;
public T remove(T t) throws Throwable;
public T find(PK pk) throws Throwable;
public List<T> findAll(String namedQuery) throws Throwable;
}
GenericServiceImpl
package me.localtest.customersapp.services;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
public abstract class GenericServiceImpl<T, PK extends Serializable> implements GenericService<T, PK> {
//#PersistenceContext(unitName="CustomersPU")
protected EntityManager em = Persistence.createEntityManagerFactory("CustomersPU").createEntityManager();
protected Class<T> clazz;
public GenericServiceImpl(Class<T> clazz) {
this.clazz = clazz;
}
#Override
public T save(T t) throws Throwable {
em.persist(t);
em.flush();
return t;
}
#Override
public T remove(T t) throws Throwable {
em.remove(t);
em.flush();
return t;
}
#Override
public T update(T t) throws Throwable {
em.merge(t);
em.flush();
return t;
}
#Override
public T find(PK pk) throws Throwable {
return (T) em.find(clazz, pk);
}
#SuppressWarnings("unchecked")
#Override
public List<T> findAll(String aQuery) throws Throwable {
Query query = em.createQuery(aQuery);
return (List<T>) query.getResultList();
}
}
CustomerServiceBean
package me.localtest.customersapp.services;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.Query;
import me.localtest.customersapp.domain.entities.Customer;
#LocalBean
#Stateless
public class CustomerServiceBean extends GenericServiceImpl<Customer, Integer> {
public CustomerServiceBean() {
super(Customer.class);
}
public Customer findByDni(String dni) {
Query query = em.createNamedQuery("Customer.findByDni");
query.setParameter("dni", dni);
return (Customer) query.getSingleResult();
}
}
Customer
package me.localtest.customersapp.domain.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name="customers")
#XmlRootElement(name="customer")
#XmlAccessorType(XmlAccessType.FIELD)
#NamedQueries({
#NamedQuery(name="Customer.findByDni", query="SELECT c FROM Customer c WHERE c.dni = :dni")
})
#SuppressWarnings("serial")
public class Customer implements Serializable {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
#XmlElement(name="id")
private Integer id;
#Column(name="names")
#XmlElement(name="names")
private String names;
#Column(name="surnames")
#XmlElement(name="surnames")
private String surnames;
#Column(name="dni")
#XmlElement(name="dni")
private String dni;
#Column(name="birth_date")
#XmlElement(name="birth-date")
#Temporal(TemporalType.DATE)
private Date birthDate;
#Column(name="address")
#XmlElement(name="address")
private String address;
#Column(name="email")
#XmlElement(name="email")
private String email;
#Column(name="creation_date")
#Temporal(TemporalType.DATE)
#XmlElement(name="creation-date")
private Date creationDate;
#Column(name="state")
#XmlElement(name="state")
private Boolean state;
public Customer() {
}
public Customer(Integer id, String names, String surnames, String dni,
Date birthDate, String address, String email, Date creationDate,
Boolean state) {
this.id = id;
this.names = names;
this.surnames = surnames;
this.dni = dni;
this.birthDate = birthDate;
this.address = address;
this.email = email;
this.creationDate = creationDate;
this.state = state;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNames() {
return names;
}
public void setNames(String names) {
this.names = names;
}
public String getSurnames() {
return surnames;
}
public void setSurnames(String surnames) {
this.surnames = surnames;
}
public String getDni() {
return dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Boolean getState() {
return state;
}
public void setState(Boolean state) {
this.state = state;
}
}
persistence.xml
<persistence-unit name="CustomersPU" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>jdbc/__customers</jta-data-source>
<properties>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
</properties>
</persistence-unit>
Stage 1
Try to find Customer with DNI 'A' (RESTful):
http://localhost:8080/customersapp/api/customers/find/A
This is a piece stack trace:
2015-04-06T09:19:31.088-0500|Advertencia: A system exception occurred during an invocation on EJB CustomerServiceBean, method: public me.localtest.customersapp.domain.entities.Customer me.localtest.customersapp.services.CustomerServiceBean.findByDni(java.lang.String)
2015-04-06T09:19:31.089-0500|Advertencia: javax.ejb.TransactionRolledbackLocalException: Exception thrown from bean
at com.sun.ejb.containers.EJBContainerTransactionManager.checkExceptionClientTx(EJBContainerTransactionManager.java:662)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:507)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy267.findByDni(Unknown Source)
at me.localtest.customersapp.services.__EJB31_Generated__CustomerServiceBean__Intf____Bean__.findByDni(Unknown Source)
And this is the cause:
Caused by: java.lang.ClassCastException: me.localtest.customersapp.domain.entities.Customer cannot be cast to me.localtest.customersapp.domain.entities.Customer
I found this stupid, how is possible can't cast to the same class?
Thanks.
Appeared to be the result of classloder problems GF 4.x is having with the hibernate version 4.3.8.Final
Most probably it relates to HHH-9446 Also it looks like it was fixed 2 days ago. Have not yet had a chance to try it though
Well, i could not find solution for this problem. I switched to WildFly 8.2.0, and no problems. Anyway, i hope someday to know why this happens xD.
Thanks.