ManyToOne annotation fails with Hibernate 4.1: MappingException - java

Using Hibernate 4.1.1.Final.
When I try to add #ManyToOne, schema creation fails with: org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.SingleTableEntityPersister
User.java:
#Entity
public class User {
#Id
private int id;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
#ManyToOne
Department department;
public Department getDepartment() {return department;}
public void setDepartment(Department department) {this.department = department;}
}
Department.java
#Entity
public class Department {
#Id
private int departmentNumber;
public int getDepartmentNumber() {return departmentNumber;}
public void setDepartmentNumber(int departmentNumber) {this.departmentNumber = departmentNumber;}
}
hibernate.properties:
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/dbname
hibernate.connection.username=user
hibernate.connection.password=pass
hibernate.connection.pool_size=5
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.hbm2ddl.auto=create
init (throwing exception):
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().buildServiceRegistry();
sessionFactory = new MetadataSources(
serviceRegistrY.addAnnotatedClass(Department.class).addAnnotatedClass(User.class).buildMetadata().buildSessionFactory();
exception throwed at init:
org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.SingleTableEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:174)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:148)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:820)
at org.hibernate.metamodel.source.internal.SessionFactoryBuilderImpl.buildSessionFactory(SessionFactoryBuilderImpl.java:65)
at org.hibernate.metamodel.source.internal.MetadataImpl.buildSessionFactory(MetadataImpl.java:340)
I have tried adding some other annotations, but shouldn't the defaults work and create the tables and foreign key? If I remove the department from User, tables get generated fine.
Thanks in advance!

You are using features not yet complete. Everything in org.hibernate.metamodel is targetting 5.0.
http://docs.jboss.org/hibernate/orm/4.1/javadocs/org/hibernate/metamodel/package-summary.html

#Entity
public class User {
#Id
private int id;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
#ManyToOne
Department department;
public Department getDepartment() {return department;}
public void setDepartment(Department department) {this.department = department;}
}
#Entity
public class Department {
#Id
private int departmentNumber;
#OneToMany(mappedBy="department")
private Set<User> user;
public Set<User> getUser() {
return user;
}
public void setUser(Set<User> user) {
this.user = user;
}
public int getDepartmentNumber() {return departmentNumber;}
public void setDepartmentNumber(int departmentNumber) {this.departmentNumber = departmentNumber;}
}
You have to add a set to the Department entity and map OneToMany Relationship with the User

My example:
User.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class User {
private int id;
private String userName;
private String password;
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
TraceLog.java
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
#Entity
public class TraceLog {
private int id;
private User user;
private String tokenId;
private String variable;
private String value;
private Date traceTime;
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#ManyToOne(cascade = CascadeType.ALL)
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Column
public String getTokenId() {
return tokenId;
}
public void setTokenId(String tokenId) {
this.tokenId = tokenId;
}
#Column
public String getVariable() {
return variable;
}
public void setVariable(String variable) {
this.variable = variable;
}
#Column
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Column
public Date getTraceTime() {
return traceTime;
}
public void setTraceTime(Date traceTime) {
this.traceTime = traceTime;
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sessiontest</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">mysql</property>
<property name="hibernate.connection.pool_size">1</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.cpviet.example.session.model.User" />
<mapping class="com.cpviet.example.session.model.TraceLog" />
</session-factory>
</hibernate-configuration>
HibernateUtil.java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private SessionFactory sessionFactory = null;
private static HibernateUtil instance = null;
private HibernateUtil() {
}
public static HibernateUtil getInstance() {
if (instance == null) {
instance = new HibernateUtil();
}
return instance;
}
public SessionFactory getSessionFactory() {
if (sessionFactory == null) {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}
}
How to use:
Session session = HibernateUtil.getInstance().getSessionFactory().openSession();
user = (User) session.get(User.class, (Integer)1);
session.close();
or
Session session = HibernateUtil.getInstance().getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
TraceLog traceLog = new TraceLog();
traceLog.setTokenId(tokenId);
traceLog.setVariable("var1");
traceLog.setValue("val1");
traceLog.setUser(user);
traceLog.setTraceTime(new Date());
session.save(traceLog);
transaction.commit();
session.close();

Related

Hibernate not generating tables

Hibernate is not generating any tables when certain tables are added to hibernate.cfg.xml:
If I add:
<mapping class="org.hibernate.tutorial.annotations.Movie"/>
<mapping class="org.hibernate.tutorial.annotations.Actor"/>
No tables are generated at all, I already have:
<property name="hibernate.hbm2ddl.auto">update</property>
In hibernate.cfg.xml, and I have already tried variations of this, I know that the issue is with these classes as other classes work fine and are auto-generated when these are not added.
Actor
package org.hibernate.tutorial.annotations;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name="ACTOR")
public class Actor {
#Id #Column(name="ACTOR_ID")
private int id;
#Column(nullable=false, unique=true)
private String name;
#ManyToMany(
targetEntity=Movie.class,
cascade={CascadeType.PERSIST, CascadeType.MERGE}
)
#JoinTable(
name="Actor_Movie",
joinColumns=#JoinColumn(name="ACTOR_ID"),
inverseJoinColumns=#JoinColumn(name="MOVIE_ID")
)
private Set<Movie> films;
public Actor(){
}
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 Set<Movie> getFilms() {
return films;
}
public void setFilms(Set<Movie> films) {
this.films = films;
}
}
Movie
import java.sql.Time;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name="MOVIE")
public class Movie {
#Id #Column(name="MOVIE_ID")
private int id;
#Column(nullable=false,unique=true)
private String title;
#ManyToMany(
targetEntity=Track.class,
cascade={CascadeType.PERSIST, CascadeType.MERGE},
mappedBy = "movies"
)
private Set<Actor> actors;
private Time playTime;
public Movie(){
}
public int getId(){
return id;
}
public String getTitle(){
return title;
}
public Set<Actor> getActors(){
return actors;
}
public Time getTime(){
return playTime;
}
public void setTime(Time playTime){
this.playTime = playTime;
}
public void setId(int id){
this.id = id;
}
public void setTitle(String name){
this.title = name;
}
public void setActors(Set<Actor> actors){
this.actors = actors;
}
}
ResetDB
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import junit.framework.TestCase;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ResetDB extends TestCase{
private SessionFactory sessionFactory;
#Override
protected void setUp() throws Exception {
// A SessionFactory is set up once for an application
sessionFactory = new Configuration()
.configure() // configures settings from hibernate.cfg.xml
.buildSessionFactory();
}
#Override
protected void tearDown() throws Exception {
if ( sessionFactory != null ) {
sessionFactory.close();
}
}
public void testResetDB() {
Session session = sessionFactory.openSession();
session.beginTransaction();
try {
Query q = session.createSQLQuery("delete from ACTOR");
q.executeUpdate();
q = session.createSQLQuery("delete from MOVIE");
q.executeUpdate();
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Exception: "+e.getLocalizedMessage());
System.out.println("Transaction rolled back");
session.getTransaction().rollback();
}
session.close();
}
}
using hibernate-core-4.1.6

Hibernate project in java perspective giving an Exception java.lang.ClassNotFoundException: javax.transaction.SystemException in Eclipse Mars

My question might look a easy and silly but I'm unable to find solution so thought of sharing the problem here... I'm getting an Exception in a simple Hibernate code running in Java perspective!! I've added JTA or transaction jar files but it's not helping!
package com.demo.bean;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="emp_details")
public class Employee{
#Id
#Column(name="emp_id")
private int id;
#Column(name="emp_name")
private String name;
private String address;
private int phone;
private double salary;
#Lob
private String description;
#Temporal(TemporalType.DATE)
private Date doj;
public Date getDoj() {
return doj;
}
public void setDoj(Date doj) {
this.doj = doj;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
package com.demo.client;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.demo.bean.Employee;
public class HibernateClient {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setId(333);
emp.setName("Guru");
emp.setAddress("Bangalore");
emp.setSalary(56565.0);
emp.setDescription("Hello");
emp.setDoj(new Date());
Configuration cfg = new Configuration();
cfg.configure("resource/hibernate.cfg.xml");
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(emp);
tx.commit();
sessionFactory.close();
}
}
<?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:3306/becm3createDatabaseIfNotExist=true</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping class="com.demo.bean.Employee"/>
</session-factory>
</hibernate-configuration>

MappingException: Type can not be determined for java.util.Set

While running following program I am getting the error
org.hibernate.MappingException: Could not determine type for: java.util.Set, for columns: [org.hibernate.mapping.Column(ListOfAddress)]
I added the import javax.persistence.ElementCollection;
But I am getting the same error
Can anyone please suggest me any option?
HibernateTest.java
package src.com.hibernate.main;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.mapping.*;
import src.com.hibernate.Address;
import src.com.hibernate.UserDetails;
public class HibernateTest {
public static void main(String[] args)
{
UserDetails user = new UserDetails();
user.setUserName("Surendar");
Address addr = new Address();
addr.setStreet("Abith colony");
addr.setCity("Chennai");
addr.setState("TamilNAdu");
addr.setPincode("600015");
Address addr1= new Address();
addr1.setStreet("Anna Salai");
addr1.setCity("Chennaimain");
addr1.setState("TN");
addr1.setPincode("600033");
user.getListOfAddress().add(addr);
user.getListOfAddress().add(addr1);
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}
UserDetails.java
package src.com.hibernate;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="UserTABLEaddress")
public class UserDetails
{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String userName;
#SuppressWarnings("rawtypes")
#ElementCollection
private Set<Address> ListOfAddress = new HashSet();
public Set<Address> getListOfAddress() {
return ListOfAddress;
}
public void setListOfAddress(Set<Address> listOfAddress) {
ListOfAddress = listOfAddress;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
Address.java
package src.com.hibernate;
import javax.persistence.Embeddable;
#Embeddable
public class Address
{
private String street;
private String city;
private String state;
private String pincode;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
Hibernate.cfg.xml
<?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:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="src.com.hibernate.UserDetails"/>
</session-factory>
</hibernate-configuration>
I think your are mixing concepts. You try to use #Embeddable annotation in a class that is used in a many-to-one relationship. That is the cause of your error.
If you want to use ListOfAddress as an element collection, you have to define Address as an entity as well and configure the relationship correctly, for example:
...
#ElementCollection
#CollectionTable(name="address", joinColumns=#JoinColumn(name="userId"))
#Column(name="addresses")
private Set<Address> ListOfAddress = new HashSet<Address>();
...
And in Address Class
#Entity
#Table(name="address")
public class Address
...
There are plenty of examples through internet.
I faced similar problem, when i changed my java compiler version from 1.6 to 1.5 it worked for me.
SO probably check if that is the case with you

Hibernate not creating a table

I am new at Hibernate Annotations and I'd like to try an example.
I have two classes (Node and HyperEdge), when I run my application, it only creates a table for Node and not for HyperEdge.
This is the code I developed:
Node :
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="Node")
public class Node {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Column
private String name;
#Column(name="\"group\"")
private Integer group;
public Node() {
super();
// TODO Auto-generated constructor stub
}
public Node(Integer id, String name, Integer group) {
super();
this.id = id;
this.name = name;
this.group = group;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getGroup() {
return group;
}
public void setGroup(Integer group) {
this.group = group;
}
}
HyperEdge :
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Table(name="HyperEdge")
public class HyperEdge {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Column
private String title;
public HyperEdge() {
super();
// TODO Auto-generated constructor stub
}
public HyperEdge(Integer id, String title) {
super();
this.id = id;
this.title = title;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
hibernate.cfg.xml :
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/exhiber</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="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="com.hib.ex.entity.Node" />
<mapping class="com.hib.ex.entity.HyperEdge" />
</session-factory>
</hibernate-configuration>
HibernateDao :
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.hib.ex.entity.HyperEdge;
import com.hib.ex.entity.Node;
public class HibExDao {
public void saveNode(Node noeud) {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(noeud);
session.getTransaction().commit();
session.close();
}
public List listNode() {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
List nodes = session.createQuery("FROM Node").list();
session.close();
return nodes;
}
public Node readNode(Integer id) {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
Node noeud = (Node) session.get(Node.class, id);
session.close();
return noeud;
}
public void saveHyperEdge(HyperEdge he, String chaine) {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
he.setTitle(chaine);
session.save(he);
session.getTransaction().commit();
session.close();
}
public List listHyperEdge() {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
List hyperedges = session.createQuery("FROM HyperEdge").list();
session.close();
return hyperedges;
}
public HyperEdge readHyperEdge(Integer id) {
SessionFactory sf = HibExUtil.getSessionFactory();
Session session = sf.openSession();
HyperEdge hyperEdge = (HyperEdge) session.get(HyperEdge.class, id);
session.close();
return hyperEdge;
}
}
The main class :
import java.util.List;
import com.hib.ex.dao.HibExDao;
import com.hib.ex.entity.HyperEdge;
import com.hib.ex.entity.Node;
public class Run {
public static void main(String[] args) {
HibExDao dao = new HibExDao();
System.out.println("****************WRITING****************");
Node n1 = new Node();
n1.setName("toto");
dao.saveNode(n1);
System.out.println("Node saved!");
Node n2 = new Node();
n2.setName("lala");
dao.saveNode(n2);
System.out.println("Node saved!");
System.out.println("\n****************READING****************");
List nodes = dao.listNode();
System.out.println("Name in Node number 2 is: " + dao.readNode(2).getName());
}
}
What is the problem? And how can I fix it?
Thanks!
Perhaps you have to add #Entity annotation to your HyperEdge class
#Entity annotation to missing from your HyperEdge class
The #Entity annotation is used to mark this class as an Entity bean. So the class should atleast have a package scope no-argument constructor.
The #Table annotation is used to specify the table to persist the data. The name attribute refers to the table name. If #Table annotation is not specified then Hibernate will by default use the class name as the table name.
In HyperEdge class you have to add #Entity annotation so that hibernate can treat it as a entity to map with table HyperEdge in database.
#Entity
#Table(name="HyperEdge")
public class HyperEdge {

Hibernate Envers dont create revisions

I have a problem with hibernate envers. I added the eventlisteners and I added the #Audited Annotation, but when I change the name (or anything else) there are no revisions in the database created. I hope you can help me.
This is the Main class where I build the session etc.
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
Address address1 = new Address();
address1.setStreetName("Privet Drive");
address1.setHouseNumber(4);
Person person1 = new Person();
person1.setName("Hi");
person1.setSurname("test");
person1.setAddress(address1);
session.beginTransaction();
session.persist(person1);
session.persist(address1);
session.getTransaction().commit();
person1.setName("Hans");
session.beginTransaction();
session.persist(person1);
session.persist(address1);
session.getTransaction().commit();
session.close();
}
}
Here the Person class:
package Main;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.envers.Audited;
import org.hibernate.envers.RevisionEntity;
import org.hibernate.envers.RevisionNumber;
import org.hibernate.envers.RevisionTimestamp;
#Entity
#Table(name="PERSON")
#Audited
public class Person{
#Id
#GeneratedValue
#RevisionNumber
private int id;
private String name;
private String surname;
private String username;
#ManyToOne
private Address address;
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public Address getAddress() {
return address;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setAddress(Address address) {
this.address = address;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
The adress:
package Main;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.envers.Audited;
#Entity
#Table(name="ADDRESS")
#Audited
public class Address {
#Id
#GeneratedValue
private int id;
private String streetName;
private Integer houseNumber;
private Integer flatNumber;
#OneToMany(mappedBy = "address")
private Set<Person> persons;
public int getId() {
return id;
}
public String getStreetName() {
return streetName;
}
public Integer getHouseNumber() {
return houseNumber;
}
public Integer getFlatNumber() {
return flatNumber;
}
public Set<Person> getPersons() {
return persons;
}
public void setId(int id) {
this.id = id;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public void setHouseNumber(Integer houseNumber) {
this.houseNumber = houseNumber;
}
public void setFlatNumber(Integer flatNumber) {
this.flatNumber = flatNumber;
}
public void setPersons(Set<Person> persons) {
this.persons = persons;
}
}
And my hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/hwdb2</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.ejb.event.post-insert">org.hibernate.ejb.event.EJB3PostInsertEventListener,org.hibernate.envers.event.AuditEventListener</property>
<property name="hibernate.ejb.event.post-update">org.hibernate.ejb.event.EJB3PostUpdateEventListener,org.hibernate.envers.event.AuditEventListener</property>
<property name="hibernate.ejb.event.post-delete">org.hibernate.ejb.event.EJB3PostDeleteEventListener,org.hibernate.envers.event.AuditEventListener</property>
<property name="hibernate.ejb.event.pre-collection-update">org.hibernate.envers.event.AuditEventListener</property>
<property name="hibernate.ejb.event.pre-collection-remove">org.hibernate.envers.event.AuditEventListener</property>
<property name="hibernate.ejb.event.post-collection-recreate">org.hibernate.envers.event.AuditEventListener</property>
<!-- Mapping files -->
<mapping class="Main.Person" />
<mapping class="Main.Address" />
<mapping class="Main.ExampleListener" />
</session-factory>
</hibernate-configuration>
I hope you have a solution for me. Many thanks!
I finally updated to Hibernate 4.1.8 and the problem is solved. I had the wrong envers version which seemed to be not compatible with the hibernate version I used.

Categories