Error message:
javax.persistence.RollbackException: Error while committing the
transaction
I'm having trouble saving user data. This error has appeared, it follows the form that the project is in:
Method to save:
public void save(User u)
{
EntityManager em = JPAUtil.getEntityManager();
EntityTransaction tx = em.getTransaction();
try
{
tx.begin();
if (u.getId_User()== null) {
em.persist(u);
} else {
em.merge(u);
}
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
if (tx != null && tx.isActive()) {
tx.rollback();
}
} finally {
em.close();
}
}
Method that receives the form data:
public String addUser(Address a, User u)
{
u.setAddress(a);
userDAO.save(u);
return "User saved successfully!";
}
Persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="consultoriowebPU">
<!-- Hibernate -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/bd_consultorioweb?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
User.class [model]:
#Entity
public class User implements Serializable
{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Long Id_User;
private String email_User;
private String name_User;
private String password_User;
private int status_User;
#ManyToOne
private Address address;
//Get and set..
}
Address.class [model]:
#Entity
public class Address implements Serializable
{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Long Id_Address;
private String Country;
private String State;
private String City;
private String Neighborhood;
private String Street;
private Long Number;
private String Complement;
private String Zipcode;
//Get and set..
}
Here is the list of libraries/jar used:
http://imgur.com/a/NDmmQ
In the console, only the insert sql appears, and then the error message and no data is recorded in the database.
I assume that the Address entity that you are populating the user with, is a detached entity.
I would add the following cascade options to the User entity:
#ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#JoinColumn(name = "address_id")
private Address address;
Now when the User entity is persisted / merged, then also the Address entity will be persisted / merged.
Related
I have a simple JPA example and I'm trying to write an entity to an H2 database.
Here is the error I am getting:
org.h2.jdbc.JdbcSQLException: Parameter "#2" is not set; SQL statement:
insert into MyEntity (name, id) values (?, ?)`
Here is my code:
EntityManagerFactory factory = Persistence.createEntityManagerFactory("thePersistenceUnit");
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
MyEntity entity = new MyEntity();
entity.setName("heyyy");
manager.persist(entity);
manager.getTransaction().commit();
My entity:
#Entity
public class MyEntity {
private String name;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
public MyEntity() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
my persistence unit
<persistence-unit name="thePersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>io.tcell.MyEntity</class>
<properties>
<property name="connection.driver_class" value="org.h2.Driver"/>
<property name="hibernate.connection.url" value="jdbc:h2:/tmp/myh2db"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
Someone to knows where can be the problem -
Could not find any META-INF/persistence.xml file in the classpath
I use IntelliJ and h2 database connection with Hibernate
There are my classes:
persistence:
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress DeprecatedClassUsageInspection -->
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="StudentPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>model.StudentInfo</class>
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.url" value="jdbc:h2:~/JPA_App" />
<property name="hibernate.connection.user" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.temp.use_jdbc_metadata_defaults"
value="false" />
</properties>
</persistence-unit>
</persistence>
Entity class:
package model;
import javax.persistence.*;
#Entity
#Table(name = "Student")
public class StudentInfo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "name", length = 30, nullable = false)
private String name;
#Column(name = "lastname", length = 30, nullable = false)
private String lastname;
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 getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
and Main class
package model;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class AddStudent {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("StudentPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
StudentInfo student = new StudentInfo();
student.setId(0);
student.setName("John");
student.setLastname("Doe");
em.persist(student);
em.getTransaction().commit();
em.close();
emf.close();
}
}
In eclipse this simple source works but in IntelliJ I received this exception.
I would be grateful for any ideas to resolve this error.
Best regards,
D. Balamjiev
Just move your META-INF folder at the root of one of build paths of your IDE.
For example, move META-INF folder to the web folder and it should be available at the runtime.
By using a build tool such as Maven or Gradle, you would not have these kinds of problem any longer since the layout is standard and therefore the same whatever the IDE you are using.
For example, in your case, it would be both for Eclipse and IntelliJ : src/main/resources/META-INF
I am creating a backend application using Spring, Hibernate and JPA.
Currently the application test pass but I get a warning:
WARN: HHH000436: Entity manager factory name (JpaPersistenceUnit) is already registered.
I think the reason for this is that I defined my JpaPersistenceUnit in the persistence.xml and I also create one in my dao class. If this is the case I need to find a way to get my JpaPersistenceUnit from the persistence.xml without creating it (again). But I don't know how...
This is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="JpaPersistenceUnit"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.archive.autodetection" value="class, hbm"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value="groepD"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/groepd"/>
<property name="hibernate.connection.username" value="groepD"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
This is my generic dao class:
public interface GenericDao<E, ID extends Serializable> {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JpaPersistenceUnit");
public void add(E entity);
public void remove(E entity);
public void update(E entity);
public E findById(ID id);
public List<E> findAll();
}
This is the specific dao class:
public interface TripDao extends GenericDao<Trip,Integer> {
}
And this is an implementation of the dao class:
#Repository
public class TripDaoImpl implements TripDao {
protected EntityManager entityManager;
public TripDaoImpl() {
entityManager = emf.createEntityManager();
}
#Override
#Transactional
public void add(Trip entity) {
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();
}
....
}
This is the entity:
#Entity
#Table(name = "T_TRIP")
public class Trip {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotNull
private String name;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name="T_TRIP_ADMINS",
joinColumns={#JoinColumn(name="tripId")},
inverseJoinColumns={#JoinColumn(name="userId")})
private Set<User> admins;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name="T_TRIP_PARTICIPANT",
joinColumns={#JoinColumn(name="tripId")},
inverseJoinColumns={#JoinColumn(name="userId")})
private Set<User> invitedUsers;
#NotNull
private Boolean privateTrip;
#NotNull
private Boolean published;
#Enumerated(EnumType.STRING)
private TripType type;
#NotNull
private Integer nrDays;
#NotNull
private Integer nrHours;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "tripId")
private Set<Stop> stops;
public Trip(){
initLists();
}
private void initLists(){
this.admins = new HashSet<User>();
this.invitedUsers = new HashSet<User>();
this.stops = new HashSet<Stop>();
}
public void addStop(Stop stop) {
stops.add(stop);
}
public boolean removeStop(Stop stop) {
if (stops.size() > 1 && stops.contains(stop)) {
stops.remove(stop);
return true;
} else {
return false;
}
}
...More getters and setters...
}
If someboby could tell me how to to fix the warning that would be very helpfull.
first: (in you applicationContext.xml)
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceXmlLocation"
value="classpath:persistence.xml">
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
<property name="loadTimeWeaver"> <!-- 运行时植入 -->
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
next:(update you code)
remove :EntityManagerFactory emf = Persistence.createEntityManagerFactory("JpaPersistenceUnit");
next: you can get the class EntityManager by this
#PersistenceContext
protected EntityManager entityManager;
ps:sorry my english is so poor,
wish helpfull for you!
I am using OpenJPA with Eclipse to persist object. I created a simple one to one unidirectional application. But it is giving Foreign key null error.
Student Entity
#Entity
public class Student implements Serializable {
#Id
private int id;
private String name;
private static final long serialVersionUID = 1L;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "dept_id", unique = true, nullable = true, insertable = true, updatable = true, referencedColumnName = "id")
private Department department;
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 Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public String toString() {
return "\n\nID:" + id + "\nName:" + name + "\n\n" + department;
}
}
Department Entity
#Entity
#Table(name = "department")
public class Department implements Serializable {
#Id
private int id;
private String name;
private static final long serialVersionUID = 1L;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String deptName) {
this.name = deptName;
}
public String toString() {
return "Department id: " + getId() + ", name: " + getName();
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="IBMJPADemo" transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>com.ibm.jpa.onetoone.model.Department</class>
<class>com.ibm.jpa.onetoone.model.Student</class>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:mysql://localhost:3306/test" />
<property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver" />
<property name="openjpa.ConnectionUserName" value="root" />
<property name="openjpa.ConnectionPassword" value="root" />
<property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO" />
<property name="openjpa.RuntimeUnenhancedClasses" value="supported"/>
<property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO"/>
<!-- property name="openjpa.jdbc.SchemaFactory" value="native(ForeignKeys=true)" /-->
<!-- property name="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict, JoinForeignKeyDeleteAction=restrict" /-->
</properties>
</persistence-unit>
</persistence>
Client Program
public class OneToOneClient {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("IBMJPADemo");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
Student student = new Student();
student.setId(2537);
student.setName("K.Senthuran");
Department dept = new Department();
dept.setId(100);
dept.setName("IT");
student.setDepartment(dept);
em.persist(student);
em.flush();
tx.commit();
em.close();
}
}
Error
Exception in thread "main" org.apache.openjpa.persistence.PersistenceException: null keys not allowed
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:1817)
at org.apache.openjpa.kernel.DelegatingBroker.flush(DelegatingBroker.java:1037)
at org.apache.openjpa.persistence.EntityManagerImpl.flush(EntityManagerImpl.java:652)
at com.ibm.jpa.onetoone.client.OneToOneClient.main(OneToOneClient.java:32)
Caused by: java.lang.NullPointerException: null keys not allowed
at org.apache.commons.collections.map.AbstractReferenceMap.put(AbstractReferenceMap.java:248)
at org.apache.openjpa.kernel.ManagedCache.assignObjectId(ManagedCache.java:189)
at org.apache.openjpa.kernel.BrokerImpl.assignObjectId(BrokerImpl.java:4949)
at org.apache.openjpa.kernel.BrokerImpl.setStateManager(BrokerImpl.java:4046)
at org.apache.openjpa.kernel.StateManagerImpl.assertObjectIdAssigned(StateManagerImpl.java:636)
at org.apache.openjpa.kernel.StateManagerImpl.afterFlush(StateManagerImpl.java:1084)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2162)
at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:2037)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:1808)
... 3 more
Please help to solve this issue.
Thanks & Regards,
K.Senthuran
Since you are using Uni-Directional Mapping, so persisting your Student will not persist your Department too. So, you need to make sure that, while persisting the Student, the Department entity reference used is already persisted in the database, else you will get exception.
So, just persist the department, before you persist the student. I think that will solve your issue.
If you want that, persisting your student also persist the department, then you would need to use bi-directional mapping. i.e. Use a reference of Student in Department, with #OneToOne mapping, specifying a mappedBy attribute.
I found the solution for this issue.
First of all we have to mention the primary key attribute with #Id and #Column annotation.
Then we have to add the following line in persistence.xml.
<property name="openjpa.jdbc.SchemaFactory" value="native(ForeignKeys=true)" />
I am using PostgreSQL(8.2) with Hibernate(3.2.5). Despite of proper annotations when I try to run my snippet at the back end, primary keys are not generated so it ends up with no record being inserted in the table.
I am trying to establish One-To-Many mapping between the tables Classroom (One side) and Student (Many side). Please find my snippet below:
Classroom class
#Entity
public class Classroom implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="room_id")
private Long id;
#Column(name="Standard")
private String std;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="room_id")
private Set<Student> students = new HashSet<Student>();
// with setters and getters
}
Student class
#Entity
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="roll_no")
private Long id;
#Column(name="name")
private String name;
// with setters and getters
}
Main class
public class Main {
public static void main(String arr[]){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("OneTomanyMyDbPU");
EntityManager em = emf.createEntityManager();
Set<Student> students = new HashSet<Student>();
Classroom c = new Classroom();
Student s1 = new Student();
Student s2 = new Student();
s1.setName("abc");
s2.setName("xyz");
students.add(s1);
students.add(s2);
c.setStd("X");
c.setStudents(students);
try {
EntityTransaction tr = em.getTransaction();
System.out.println("Classroom b4 persisting...:"+c.getStd());
em.persist(c);
tr.commit();
} catch(Exception e){
}
}
}
persistence.xml
<persistence-unit name="OneTomanyMyDbPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class> model.Classroom</class>
<class> model.Student</class>
<properties>
<property name="hibernate.connection.username" value="postgres"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.connection.password" value="abc123"/>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost/mydb"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
What can be the cause? How to persist them?
Your hbm file says ddl to be updated, so you never know if everytime tables are being created, so instead of this :
catch(Exception e){
}
can you place this :
catch(Exception e){
e.printStackTrace();
}
and rerun