Error with JPA persistence.xml No Persistence provider for EntityManager - java

I have 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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.vyhn</groupId>
<artifactId>jpa</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>jpa Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.core</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.2</version>
</dependency>
</dependencies>
<build>
<finalName>jpa</finalName>
</build>
</project>
Employee.java
package example.com.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
#Entity
public class Employee {
#Id
#GeneratedValue
private Long id;
private String name;
#ManyToOne
private Department department;
public Employee() {
}
public Employee(String name, Department department) {
this.name = name;
this.department = department;
}
public Employee(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
#Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", department="
+ department.getName() + "]";
}
}
Department.java
package example.com.domain;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
#Entity
public class Department {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToMany(mappedBy = "department", cascade = CascadeType.PERSIST)
private List<Employee> employees = new ArrayList<Employee>();
public Department() {
super();
}
public Department(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
JpaTest.java
package example.com.jpa;
import example.com.domain.Department;
import example.com.domain.Employee;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;
public class JpaTest {
private EntityManager manager;
public JpaTest(EntityManager manager) {
this.manager = manager;
}
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnit");
EntityManager manager = factory.createEntityManager();
JpaTest test = new JpaTest(manager);
EntityTransaction tx = manager.getTransaction();
tx.begin();
try {
test.createEmployees();
} catch (Exception e) {
e.printStackTrace();
}
tx.commit();
test.listEmployees();
System.out.println(".. done");
}
private void createEmployees() {
int numOfEmployees = manager.createQuery("Select a From Employee a", Employee.class).getResultList().size();
if (numOfEmployees == 0) {
Department department = new Department("java");
manager.persist(department);
manager.persist(new Employee("Jakab Gipsz", department));
manager.persist(new Employee("Captain Nemo", department));
}
}
private void listEmployees() {
List<Employee> resultList = manager.createQuery("Select a From Employee a", Employee.class).getResultList();
System.out.println("num of employess:" + resultList.size());
for (Employee next : resultList) {
System.out.println("next employee: " + next);
}
}
}
When I run JpaTest.java, has error:
"C:\Program Files\Java\jdk1.8.0_92\bin\java" -Didea.launcher.port=7533 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.1.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_92\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_92\jre\lib\rt.jar;C:\Users\Administrator\IdeaProjects\demo_jpa\target\classes;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\eclipselink\2.6.3\eclipselink-2.6.3.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\javax.persistence\2.1.1\javax.persistence-2.1.1.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\commonj.sdo\2.1.1\commonj.sdo-2.1.1.jar;C:\Users\Administrator\.m2\repository\javax\validation\validation-api\1.1.0.Final\validation-api-1.1.0.Final.jar;C:\Users\Administrator\.m2\repository\org\glassfish\javax.json\1.0.4\javax.json-1.0.4.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\org.eclipse.persistence.core\2.6.3\org.eclipse.persistence.core-2.6.3.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\org.eclipse.persistence.asm\2.6.3\org.eclipse.persistence.asm-2.6.3.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\org.eclipse.persistence.jpa\2.6.3\org.eclipse.persistence.jpa-2.6.3.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\org.eclipse.persistence.antlr\2.6.3\org.eclipse.persistence.antlr-2.6.3.jar;C:\Users\Administrator\.m2\repository\org\eclipse\persistence\org.eclipse.persistence.jpa.jpql\2.6.3\org.eclipse.persistence.jpa.jpql-2.6.3.jar;C:\Users\Administrator\.m2\repository\javax\persistence\persistence-api\1.0.2\persistence-api-1.0.2.jar;C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\6.0.2\mysql-connector-java-6.0.2.jar;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.1.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain example.com.jpa.JpaTest
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named persistenceUnit
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:85)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at example.com.jpa.JpaTest.main(JpaTest.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Help me fix this error, thank you!

You have to put persistence.xml in java/resources folder.
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
I hope this will work

Related

No qualifying bean of type 'com.jpa.dao.UserRepository' available

I am trying String JPA for the first time.
I was following a Youtube video by Durgesh Sir.
This is the error
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.jpa.dao.UserRepository' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1177)
at com.jpa.demo.BootjpaApplication.main(BootjpaApplication.java:13)
Following are my files
BootjpaApplication.java (which contains main)
package com.jpa.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.jpa.dao.UserRepository;
import com.jpa.entities.user;
#SpringBootApplication
public class BootjpaApplication {
public static void main(String[] args) {
ApplicationContext context= SpringApplication.run(BootjpaApplication.class, args);
UserRepository userrepo= context.getBean(UserRepository.class);
user user=new user();
user.setName("Varun Dhawan");
user.setCity("Paris");
user.setStatus("happy");
user user1= userrepo.save(user);
System.out.println(user1);
}
user.java (there are 4 variables. id is auto generated. Other 3 have getters and setters.
package com.jpa.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class user {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
private int id;
private String name;
private String city;
private String status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public user(int id, String name, String city, String status) {
super();
this.id = id;
this.name = name;
this.city = city;
this.status = status;
}
public user() {
super();
// TODO Auto-generated constructor stub
}
#Override
public String toString() {
return "user [id=" + id + ", name=" + name + ", city=" + city + ", status=" + status + "]";
}
}
UserRepository.java
package com.jpa.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.jpa.entities.user;
#Repository
public interface UserRepository extends JpaRepository<user,Integer> {
}
Application.properties
spring.datasource.name=jpa
spring.datasource.url=jdbc:mysql://localhost:3306/jpa
spring.datasource.username=root
spring.datasource.password=root#123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto=update
Thank you!
It looks like your packages are not scanned properly.
Can you please try adding #SpringBootApplication(scanBasePackages = "com.jpa") instead of #SpringBootApplication.
just create a single package(forget about coupling for a bit and do that). Then put all the classes(POJO , Main) and Interface(UserRepository) in side that package and re-start your project. It will work.
your package structure should be like this,
com.spring
com.spring.DAO
com.spring.Model
com.spring.View
com.spring.Controller
In pom.xml file checks for hibernate and JPA configuration
Same bug occur in my application
I resolve it by adding configuration
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Thank you !
I had the same issues with Repository not being found. So what I did was to move everything into 1 package. And this worked meaning that there was nothing wrong with my code. I moved the Repos & Entities into another package and added the following to SpringApplication class.
#EnableJpaRepositories("com...jpa")
#EntityScan("com...jpa")
After that, I moved the Service (interface & implementation) to another package and added the following to SpringApplication class.
#ComponentScan("com...service")
This solved my issues.

Spring Boot & Couchbase Stack Overflow

Hi I have 2 simple classes in a bidirectional relationship which are causing infinite recursion resulting in an eventual stack overflow when serialising into JSON. I am using the Spring Boot 2.2.2 starter project for Couchbase and Spring Web dependencies. My maven pom.xml file is as follows:
<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.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.stevie</groupId>
<artifactId>stack-overflow-error</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>stack-overflow-error</name>
<description>Reproduce Couchbase API Failure</description>
<properties>
<java.version>13</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-couchbase</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-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>
My domain classes are as follows:
Household.java
import org.springframework.data.couchbase.core.mapping.Document;
import com.couchbase.client.java.repository.annotation.Field;
import com.couchbase.client.java.repository.annotation.Id;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#Document
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "#id")
public final class Household {
#Id
private final String key;
#Field
private String type = "household";
#Field
private final String headSurname;
#Field
private final String headForename;
#Field
private final List<Member> members;
public static Household of(String key, String headSurname, String headForename) {
return new Household(key, headSurname, headForename);
}
Household(String key, String headSurname, String headForename) {
super();
this.key = key;
this.headSurname = headSurname;
this.headForename = headForename;
this.members = new ArrayList<>();
}
public String getKey() {
return key;
}
public String getHeadSurname() {
return headSurname;
}
public String getHeadForename() {
return headForename;
}
#JsonManagedReference
public List<Member> getMembers() {
return members;
}
#Override
public String toString() {
return String.format("Household [key=%s, headSurname=%s, headForename=%s]", key,
headSurname, headForename);
}
}
Member.java
import org.springframework.data.couchbase.core.mapping.Document;
import com.couchbase.client.java.repository.annotation.Field;
import com.couchbase.client.java.repository.annotation.Id;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#Document
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "#id")
public final class Member {
#Id
private final String key;
#Field
private final String name;
#Field
private final Household household;
public static Member of(String key, String name, Household household) {
return new Member(key, name, household);
}
Member(String key, String name, Household household) {
super();
this.key = key;
this.name = name;
this.household = household;
}
public String getKey() {
return key;
}
public String getName() {
return name;
}
#JsonBackReference
public Household getHousehold() {
return household;
}
#Override
public String toString() {
return String.format(
"Member [key=%s, name=%s]", key, name);
}
}
My unit test (JUnit 5) is
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import org.stevie.overflow.StackOverflowErrorApplication;
import org.stevie.overflow.domain.Household;
import org.stevie.overflow.domain.Member;
import com.couchbase.client.java.Bucket;
#SpringBootTest(classes = StackOverflowErrorApplication.class)
class HouseholdRepositoryTest {
#Autowired
private HouseholdRepository repo;
#Autowired
private CouchbaseTemplate template;
#BeforeAll
static void setUpBeforeClass() throws Exception {
}
#AfterAll
static void tearDownAfterClass() throws Exception {
}
#BeforeEach
void setUp() throws Exception {
}
#AfterEach
void tearDown() throws Exception {
}
#Test
void throwsStackOverflowExceptionTest() {
String key = manuallyGenerateKey("household");
Household house = Household.of(key, "BLOGGS", "Joe");
key = manuallyGenerateKey("member");
Member m1 = Member.of(key, "Joe Bloggs", house);
house.getMembers().add(m1);
/** Following code throws Stack overflow exception!!!!! **/
house = repo.save(house);
}
private String manuallyGenerateKey(String prefix) {
Bucket bucket = template.getCouchbaseBucket();
Long nextId = bucket.counter("counter::" + prefix, 1, 100).content();
String key = prefix + "::" + nextId;
return key;
}
}
I want the JSON for the household to contain its member objects and the member to contain its household object. I have tried Jackson annotations such as #JsonManagedReference and #JsonIdentityInfo but Spring appears to ignore them. Thanks.

Hibernate MAPPING error with persistence class

Hello everyone I am making a web-app and having some problems. I am sharing my codes as well as problems.
and here is my dao
package service;
import java.util.List;
import com.blog.mapperclass.UserData;
public interface UserService {
public void addUser(UserData data);
//public List <UserData> getAllUsers();
}
this is my DAO implementation
package com.blog.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.stereotype.Component;
import com.blog.mapperclass.UserData;
import service.UserService;
#Component
public class Usersdao implements UserService{
SessionFactory session= new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
#Override
public void addUser(UserData data) {
Session ses=session.openSession();
ses.beginTransaction();
ses.save(data);
ses.getTransaction().commit();
System.out.println("user added");
}
}
my request mapping
#RequestMapping("/submit")
public String showSubmit(#ModelAttribute UserData data){
dao.addUser(data);
return "submit";
}
my cfg file
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:8086/blog</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">validate</property>
<mapping class="com.blog.mapperclass.UserData"></mapping>
</session-factory>
</hibernate-configuration>
and here is the error
Constructor threw exception; nested exception is org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.blog.mapperclass.UserData"/>
and when I use :
SessionFactory session= new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
it gives error
Failed to instantiate [com.blog.dao.Usersdao]: Constructor threw exception; nested exception is java.lang.IncompatibleClassChangeError: Implementing class
And all my jars are updated
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.5-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.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.springframework</groupId>
<artifactId>spring-hibernate3</artifactId>
<version>2.0.8</version>
</dependency>
Please tell me the some solution for the problem I am newbie.
P.S : here is my pojo class
package com.blog.mapperclass;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
#Entity
#Table(name="users")
#Component
public class UserData {
#Id
#Column
private String user_id;
#Column
private String name;
#Column
private String password;
#Column
private String email;
#Column
private String phone;
#Column
private int roll_id;
public UserData(String user_id, String name, String password, String email, String phone, int roll_id) {
super();
this.user_id = user_id;
this.name = name;
this.password = password;
this.email = email;
this.phone = phone;
this.roll_id = roll_id;
}
public UserData(){}
public UserData(String name, String password, String email, String phone) {
this.name = name;
this.password = password;
this.email = email;
this.phone = phone;
}
public UserData(String user_id, String name, String password, String email, String phone) {
super();
this.user_id = user_id;
this.name = name;
this.password = password;
this.email = email;
this.phone = phone;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
and my sql table :
click here for image

Detached entity error caused by cascade attribute

I am newbie with JPA and Hibernate. I have the two entities, Vendor and Product, described below.
#Entity
public class Vendor extends BaseEntity
{
private static final long serialVersionUID = 267250313080292374L;
#NotNull
private String name;
#NotNull
private String city;
#OneToMany(mappedBy = "vendor", cascade = CascadeType.ALL)
private List<Product> products = new ArrayList<Product>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
#Entity
public class Product extends BaseEntity
{
private static final long serialVersionUID = -4676899182130380017L;
#NotNull
private String name;
#Column(nullable = false, precision = 10, scale = 2)
private double price;
#NotNull
private int quantity;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="VENDOR_ID", nullable = false)
private Vendor vendor;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Vendor getVendor() {
return vendor;
}
public void setVendor(Vendor vendor) {
this.vendor = vendor;
}
}
My problem is related to the usage of the attribute nullable = false in the #ManyToOne annotation. I want that the corresponding column annotated with #ManyToOne to be not null. However when I test the persitence of the entities with the following test:
public void testCreateEntity()
{
// create vendor1, set name and city
vendor1 = new Vendor();
vendor1.setName("MediaMarkt");
vendor1.setCity("Berlin");
vendor1 = service.createOrUpdateEntity(vendor1);
// create product1, set name, price and quantity
product1 = new Product();
product1.setName("Samsung Galaxy S7");
product1.setPrice(new Double("819.00"));
product1.setQuantity(1);
vendor1.getProducts().add(product1);
product1.setVendor(vendor1);
// create product at service
product1 = service.createOrUpdateEntity(product1);
...
}
where the createOrUpdateEntity method is part of a DAO Bean Object
#PersistenceContext
private EntityManager em;
public <T extends BaseEntity> T createOrUpdateEntity(T entity)
{
// as we have no id yet, it must be freshly brewed
if (entity.getId() == 0)
{
log.debug("createOrUpdateEntity::create:: {}", entity);
this.em.persist(entity);
}
// if there is an id, we must have dealt with it before
else
{
log.debug("createOrUpdateEntity::update:: {}", entity);
this.em.merge(entity);
}
this.em.flush();
return entity;
}
I get the error:
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: de.brockhaus.stock.entity.Stock
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:124)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:765)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:758)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener$1.cascade(JpaPersistEventListener.java:80)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:398)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:323)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:162)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:111)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:425)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:249)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:178)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:121)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:775)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:748)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:753)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1146)
... 138 more
EDIT: Implementing this example, which uses a #ManyToOne column annotated as nullable = false, I have realized that my problem is not related to this. Such as shown in the previous server log, the problem is being caused by the Cascade class. Some solutions in SO suggest to change CascadeType.ALL by CascadeType.MERGE. Other ones show different strategies. Even some ones tell that only the OneToMany side of the association should use cascade. Frankly, I thought that using CascadeType.ALL in both sides of the association was the best option. But it seems that I was wrong. Although, such as I have pointed out, I am newbie with JPA and Hibernate and I do not understand the reasonings.
You can use optional tag for null control:
#ManyToOne(cascade = CascadeType.ALL, optional = false)
#JoinColumn(name="VENDOR_ID")
private Vendor vendor;
Actually, with this code, I can get your example to work:
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>demo</groupId>
<artifactId>hibernate4-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>hibernate4-demo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<hibernate-core.version>4.3.11.Final</hibernate-core.version>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-core.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-core.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
BaseEntity.java (curtesy of Brockhaus)
package demo.hibernate4;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
#MappedSuperclass
public abstract class BaseEntity implements Serializable {
#Version
private long version;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Temporal(TemporalType.DATE)
private Date creationDate;
public BaseEntity() {
//lazy
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public long getId() {
return id;
}
}
GenericDAOBean.java
package demo.hibernate4;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
public class GenericDAOBean {
private EntityManager em;
#Override
public <T extends BaseEntity> T createOrUpdateEntity(T entity) {
if (entity.getId() == 0) {
this.em.persist(entity);
} else {
this.em.merge(entity);
}
this.em.flush();
return entity;
}
public void setEm(EntityManager em) {
this.em = em;
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="hibernate4-demo" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="javax.persistence.schema-generation.database.action" value="none"/>
</properties>
</persistence-unit>
</persistence>
Main.java
package demo.hibernate4;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hibernate4-demo");
EntityManager em = emf.createEntityManager();
GenericDAOBean service = new GenericDAOBean();
service.setEm(em);
EntityTransaction transaction = em.getTransaction();
transaction.begin();
// create vendor1, set name and city
Vendor vendor1 = new Vendor();
vendor1.setName("MediaMarkt");
vendor1.setCity("Berlin");
vendor1 = service.createOrUpdateEntity(vendor1);
// create product1, set name, price and quantity
Product product1 = new Product();
product1.setName("Samsung Galaxy S7");
product1.setPrice(new Double("819.00"));
product1.setQuantity(1);
vendor1.getProducts().add(product1);
product1.setVendor(vendor1);
// create product at service
product1 = service.createOrUpdateEntity(product1);
transaction.commit();
System.exit(0);
}
}
With this code and your mapping, I get 2 rows in MySQL and the relationship between the Product and the Vendor is established.
However, I don't understand what you're trying to achieve with your list of vendor keys. For the moment, the table PRODUCT_VENDORKEY stays empty.
You'll have to describe your context further.

spring boot data jpa mysql could not create database

I am new in spring
I will post my code,
that the application.properties
spring.datasource.url=jdbc:mysql://localhost/spring
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto=update
and this my entity
package model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String phone;
private String adresse;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public Person(long id, String name, String phone, String adresse) {
super();
this.id = id;
this.name = name;
this.phone = phone;
this.adresse = adresse;
}
public Person() {
super();
}
}
and this is the repository
package repositry;
import org.springframework.data.jpa.repository.JpaRepository;
import model.Person;
public interface PersonRespositry extends JpaRepository<Person, Long> {
}
and my controller
package contoller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import model.Person;
import repositry.PersonRespositry;
#RestController
public class PersonController {
PersonRespositry rp;
#Autowired
public PersonController(PersonRespositry rp) {
// TODO Auto-generated constructor stub
this.rp=rp;
}
#RequestMapping("/find")
public Person find(long id){
return rp.findOne(id);
}
#RequestMapping("/findall")
public List<Person> findall(){
return rp.findAll();
}
#RequestMapping(value="/hello")
public String Demo(){
return "Hello world !!";
}
#RequestMapping(value="/create", method=RequestMethod.GET)
public String create(){
Person p=new Person();
p.setName("med");
p.setPhone("233888");
p.setAdresse("rue ");
rp.save(p);
return " success";
}
}
This is the architect of the project:
When I run the application the database does not generate and only the
localhost:8080 is running.
Your problem is the location of the Application.java.
#ComponentScanlooks for Spring beans inside the package of the class annotated with (#SpringBootApplication contains #ComponentScan) and in subpackages of this package.
I already provided an example to a very similar setup.
Please have a look here: https://stackoverflow.com/a/27983870/2576531
Furthermore the hint of Robert Moskal is correct. The database itself has to exist already. Only the tables will be created automatically.
If you want the data to be created you need to use create or create-drop. If you are using something like mysql you'll need to have created at least the database. The tables will be created for you.
I be very careful about doing this against a production database instance.
Otherwise for me it dosen't work with #componentScan but it works now with #EntityScan(basePackages = { "com.jwt.entites" }) in the main class to scan entity classes ..
This is not the answer but this is a sample. I think this will help you
//Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 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.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wisdom.spring.myjdbc</groupId>
<artifactId>spring_boot_jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring_boot_jpa</name>
<description>Demo project for Spring Boot</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.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>
//application Config
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/wisdom
spring.datasource.username=root
spring.datasource.password=8855
spring.jpa.generate-ddl=true
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
server.port = 8585
package com.wisdom.spring.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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wisdom.spring.model.students;
import com.wisdom.spring.repo.students_repo;
#RestController
#RequestMapping("/students")
public class studentController {
#Autowired
students_repo STDRepo;
#GetMapping(value = "/a")
public String a() {
return "hello";
}
#GetMapping(value = "/save")
public List<students> getStudents(){
System.out.println("Data returned");
return STDRepo.findAll();
}
#PostMapping(value = "/savestd")
public void saveBurger(students student) {
STDRepo.save(student);
}
}
package com.wisdom.spring.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class students {
#Id
#Column
private int s_id;
#Column
private String name;
#Column
private String address;
public students() {
}
public students(int s_id, String name, String address) {
this.s_id = s_id;
this.name = name;
this.address = address;
}
public int getS_id() {
return s_id;
}
public void setS_id(int s_id) {
this.s_id = s_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
package com.wisdom.spring.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.wisdom.spring.model.students;
public interface students_repo extends JpaRepository<students,String> {
}
package com.wisdom.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootJpaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootJpaApplication.class, args);
}
}

Categories

Resources