I was reading some interview questions on Hibernate and came across Hibernate derived properties. I was trying a simple example using #Formula annotations but it is not working. Can anyone please tell me what am i missing. Code snippets below
The output and the SQL queries are display at the end.
Entity (Employee.java)
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Formula;
#Entity
#Table(name="EMPLOYEE")
public class Employee implements java.io.Serializable {
private static final long serialVersionUID = -7311873726885796936L;
#Id
#Column(name="ID")
private Integer id;
#Column(name="FIRST_NAME", length=31)
private String firstName;
#Column(name="LAST_NAME", length=31)
private String lastName;
#Column(name="MONTHLY_SALARY")
private float monthlySalary;
#Formula("MONTHLY_SALARY*12")
private float yearlySalary;
public Employee() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public float getMonthlySalary() {
return monthlySalary;
}
public void setMonthlySalary(float monthlySalary) {
this.monthlySalary = monthlySalary;
}
public float getYearlySalary() {
return yearlySalary;
}
}
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9iDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">system</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:XE</property>
<property name="hibernate.cache.use_query_cache">false</property>
<property name="hibernate.jdbc.use_streams_for_binary">true</property>
<property name="hibernate.jdbc.batch_size">0</property>
<property name="hibernate.max_fetch_depth">3</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name ="show_sql">true</property>
<mapping class="Employee"/>
<!-- <mapping class="dto.UserDetailsEmbeddedId"/>-->
</session-factory>
</hibernate-configuration>
Tester class
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SessionFactory factory = (new Configuration()).configure().buildSessionFactory();
Session session = factory.openSession();
Employee employee = new Employee();
employee.setFirstName("Tarun");
employee.setLastName("bhatt");
employee.setMonthlySalary(34000);
employee.setId(12);
session.beginTransaction();
session.save(employee);
session.getTransaction().commit();
System.out.println("salary1 = "+employee.getYearlySalary());
session.close();
System.out.println("salary = "+employee.getYearlySalary());
}
}
Output
salary1 = 0.0
salary = 0.0
Queries
Hibernate: create table EMPLOYEE (ID number(10,0) not null, FIRST_NAME varchar2(31 char), LAST_NAME varchar2(31 char), MONTHLY_SALARY float, primary key (ID))
Hibernate: insert into EMPLOYEE (FIRST_NAME, LAST_NAME, MONTHLY_SALARY, ID) values (?, ?, ?, ?)
#Formula annotation is intended to be used during data-retrivial (SELECT in few words) so a read of and Employee looks as
select ID,FIRST_NAME,LAST_NAME,MONTHLY_SALARY,MONTHLY_SALARY*12 as yearlySalary
#Formula doesn't works for insertion or update
Related
Here is the exception i am facing, it occurs when i call session.save
object.org.hibernate.MappingException: Unknown entity:
com.java.learn.pojo.Employee
here is my java code
try
{
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder =
new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
Session session = factory.openSession();
Employee e = new Employee(1, "", "", 3);
e.setFirstName("sparsh");
session.save(e);
System.out.println("in dao");
}
catch (Throwable ex)
{
System.err.println("Failed to create sessionFactory object." + ex);
factory.close();
throw new ExceptionInInitializerError(ex);
}
and here is my hibrnate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume students is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/test
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root1
</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping class="com.java.learn.pojo.Employee"/>
</session-factory>
</hibernate-configuration>
this exception occurs because of no mapping for Pojo class, but I have added it.
Pojo class
package com.java.learn.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Table
#Entity
public class Employee
{
#Id
#GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "salary")
private int salary;
public Employee()
{
}
public Employee(int id, String firstName, String lastName, int salary)
{
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String first_name)
{
this.firstName = first_name;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String last_name)
{
this.lastName = last_name;
}
public int getSalary()
{
return salary;
}
public void setSalary(int salary)
{
this.salary = salary;
}
}
Please help
You can use new Configuration().configure() to load the Entity mappings from hbm.xml files.
But because you are using annotations for your Employee Entity class, you simply need to use AnnotationConfiguration instead of Configuration as shown below:
So, replace the line below:
Configuration configuration = new Configuration().configure();
with:
Configuration configuration = new AnnotationConfiguration().configure();
Problem:
The problem is obvious here, you have not correctly mapped your Employee entity which is so relevant from the error stack trace:
object.org.hibernate.MappingException: Unknown entity: com.java.learn.pojo.Employee
And the problem is that the mapped entity in your hibernate.cfg.xml configuration file can't be reached because you placed your file under web-inf/classes so when hibernate tries to look for your Entity it will look for it under web-inf/classes and it won't find it.
Solution:
To solve this problem you just need to place your hibernate.cfg.xml file under Java/src folder instead of web-inf/classes so the Entity can be reached.
I am trying to execute a basic hibernate application.However,I am consistently getting the error that is posted in the question.
Below posted is my project structure code:
Below is the code that is present in app.java
public class app {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Session session =hibernate_utils.getSessionFactory().openSession();
session.beginTransaction();
contact contact=new contact();
contact.setFirstname("xxx");
contact.setLastname("xxx");
contact.setEmail("xxxxxxx#gmail.com");
contact.setTelephone("xxxxxxxxxx");
session.save(contact);
session.getTransaction().commit();
System.out.println("saved");
}
}
Below posted is the code that is present in the contact.java file
package net.rishanth.contact.form;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Column;
import static javax.persistence.GenerationType.SEQUENCE;
#Entity
#Table(name = "contacts")
public class contact {
#Id
#GeneratedValue(strategy=SEQUENCE)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "firstname", nullable = false)
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
#Column(name = "lastname", nullable = false)
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Column(name = "email", nullable = false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "telephone", nullable = false)
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
private String firstname;
private String lastname;
private String email;
private String telephone;
private Integer id;
}
Below posted is the code for my hiber_utils class present in service package.
package net.rishanth.contact.service;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class hibernate_utils {
private static final SessionFactory sessionfactory= buildSessionFatory();
#SuppressWarnings("deprecation")
private static SessionFactory buildSessionFatory(){
// TODO Auto-generated method stub
return new Configuration().configure().buildSessionFactory();
}
public static SessionFactory getSessionFactory()
{
return sessionfactory;
}
public static void shutdown()
{
getSessionFactory().close();
}
}
Below present is the hibernate.cnfg.xml file
<?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>
<property
name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property
name="hibernate.connection.url">jdbc:oracle:thin:#127.0.0.1:1521:XE
</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect
</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">xxxxx</property>
<mapping class="net.rishanth.contact.form.contact"></mapping>
</session-factory>
</hibernate-configuration>
Below attached is my oracle screenshot
Any help would be highly appreciated.
Thanks!
You have annotated the Contact entity use SEQUENCE as strategy. But you have not specified which sequence should be used. (I believe this is the error you might be getting. If not, posting the exception stack trace will help.)
In this case, by default hibernate looks for a sequence named hibernate_sequence and creating a sequence with this name should help.
Or, In case you want hibernate to use a sequence (say, your_sequence_name) that you have already created then further qualifying the #Id attribute as below should help:
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="mySeq")
#GenericGenerator(name="mySeq", strategy="sequence",
parameters={
#Parameter(name="sequence_name", value="your_sequence_name")
})
Usually we need not to create the table/sequence in our DB, hibernate can manage the same.
For that you need to add below tag in your hibernate.cfg.xml
<property name="hbm2ddl.auto">create</property>
hbm2ddl.auto have few possible values:
create : When you create SessionFactory, hibernate drop everything(if exist) and create it again for you.
create-drop : create everything on start-up and drop them on shut-down
update : update the schema.
validate : validate the schema, makes no changes to the database.
Anyway, if you want to create table/sequence explicitly, you can create them.
But then while using #GeneratedValue you have to specify your sequence.
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 {
I am new to the concepts of hibernate and annotations .Currently I am making program on collections in hibernate.
Actually following is code of my program
person.class
package com;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "PesonSubjects")
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
#ElementCollection
private Set<Subjects> subjectList = new HashSet<Subjects>();
public Set<Subjects> getSubjectList() {
return subjectList;
}
public void setSubjectList(Set<Subjects> subjectList) {
this.subjectList = subjectList;
}
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;
}
}
MAIN class
package com;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class Personmain {
/**
* #param args
*/
public static void main(String[] args) {
SessionFactory sessionfactory = new AnnotationConfiguration()
.configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
Person person = new Person();
person.setName("vikram");
Subjects subjects1 = new Subjects();
subjects1.setAuthor("xxxxxxxx");
subjects1.setISBN(10111);
subjects1.setName("mein kampf");
subjects1.setPublicationHouse("tmh");
person.getSubjectList().add(subjects1);
Subjects subjects2 = new Subjects();
subjects2.setAuthor("bbbbb");
subjects2.setISBN(10112);
subjects2.setName("harry porter");
subjects2.setPublicationHouse("William");
person.getSubjectList().add(subjects2);
session.save(person);
session.getTransaction().commit();
session.close();
}
}
subjects class
package com;
import javax.persistence.Embeddable;
#Embeddable
public class Subjects {
private int ISBN;
private String name;
private String Author;
private String publicationHouse;
public int getISBN() {
return ISBN;
}
public void setISBN(int iSBN) {
ISBN = iSBN;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return Author;
}
public void setAuthor(String author) {
Author = author;
}
public String getPublicationHouse() {
return publicationHouse;
}
public void setPublicationHouse(String publicationHouse) {
this.publicationHouse = publicationHouse;
}
}
my configuration file
<?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/AnnotationCollections</property>
<property name="connection.username">root</property>
<property name="connection.password">cccccccc</property>
<property name="hbm2ddl.auto">create</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping class="com.Person" />
</session-factory>
</hibernate-configuration>
Now through the program I want a collection of subjects to enter into a table (I am not annotating subjectList as i want it to be collection and not in tabular format)
ie it should store values in collection fomat
However I am getting the following error
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: java.util.Set, for columns: [org.hibernate.mapping.Column(subjectList)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:266)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:253)
at org.hibernate.mapping.Property.isValid(Property.java:185)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:410)
at org.hibernate.mapping.RootClass.validate(RootClass.java:192)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1099)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1284)
at com.Personmain.main(Personmain.java:14)
Is there something else to define ??
Thanks
For security's sake, keep both classes mapped:
<mapping class="com.Person" />
<mapping class="com.Subjects" />
Besides that, your code seems to be inferring the wrong access type.
Try adding:
#javax.persistence.Access(javax.persistence.AccessType.FIELD)
to Person. Like:
#Entity
#Table(name = "PesonSubjects")
#javax.persistence.Access(javax.persistence.AccessType.FIELD)
public class Person {
If that does not work, try adding to both Person and Subjects.
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.