How does #OrderBy work?
It is not working here in the following code:
Employee.java
package com.semanticbits.pojo;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
#Entity
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int employeeId;
private String name;
private double salary;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="EMP_ID")
#OrderBy("city DESC")
private List<Address> address;
//setters and getters
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
}
Address.java
package com.semanticbits.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Address {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int addressId;
private String street;
private String city;
private String state;
private int zipCode;
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 int getZipCode() {
return zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<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_1_0.xsd" version="1.0">
<persistence-unit name="orderbyannotationdemo" transaction-type="RESOURCE_LOCAL">
<provider></provider>
<class>com.semanticbits.pojo.Employee</class>
<class>com.semanticbits.pojo.Address</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/shoaib"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
This is the test class......check out the city name and it is not storing address values in order in descending order in the ADDRESS table
JPAOrderByAnnotationTest
package com.semanticbits.test;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.semanticbits.pojo.Address;
import com.semanticbits.pojo.Employee;
public class JPAOrderByAnnotationTest {
/**
* #param args
*/
public static void main(String[] args) {
EntityManagerFactory factory=Persistence.createEntityManagerFactory("orderbyannotationdemo");
EntityManager manager=factory.createEntityManager();
Employee employee=new Employee();
employee.setName("Shoaib");
employee.setSalary(1452365);
Address addressOffice=new Address();
addressOffice.setCity("Hyderabad");
addressOffice.setStreet("Gachibowli");
addressOffice.setState("AP");
addressOffice.setZipCode(500016);
Address addressHome=new Address();
addressHome.setCity("Noida");
addressHome.setStreet("Chandai Chowk");
addressHome.setState("UP");
addressHome.setZipCode(415608);
Address addressCollege=new Address();
addressCollege.setCity("Antartica");
addressCollege.setState("Canada");
addressCollege.setStreet("New York");
addressCollege.setZipCode(402103);
List<Address> addresses=new ArrayList<Address>();
addresses.add(addressHome);
addresses.add(addressOffice);
addresses.add(addressCollege);
employee.setAddress(addresses);
manager.getTransaction().begin();
manager.persist(employee);
manager.getTransaction().commit();
manager.close();
}
}
I think you're misunderstanding what the #Orderby annotation actually does. According to the javadoc:
Specifies the ordering of the elements of a collection valued
association or element collection at the point when the association or
collection is retrieved.
[emphasis added] The annotation does not dictate insertion order. Continuing with your example, if you were to fetch an Employee:
Employee employee = manager.find(Employee.class, employeeId);
List<Address> addresses = employee.getAddress();
Then addresses would be sorted by city in descending order.
according to the spec you would have to use:
#OrderBy("address.city DESC")
Related
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>
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
when i ran my code at first it worked correctly but later i am unable access those
tables?
Here is my code:-
hibernate.cfg.xml
<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/navlic</property>
<property name="connection.username">root</property>
<property name="connection.password">root</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>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="dto.UserDetails"/>
</session-factory>
</hibernate-configuration>
Main class:-
package dto;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GenerationType;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.CollectionId;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateTest {
public static void main(String[] args) {
UserDetails ud=new UserDetails();
ud.setUserName("Second user");
Address homead=new Address();
homead.setCity("smg");
homead.setCountry("aa");
homead.setHouse("bb");
homead.setStreet("cc");
homead.setState("dd");
Address officead=new Address();
officead.setCity("smg");
officead.setCountry("ee");
officead.setHouse("ff");
officead.setStreet("gg");
officead.setState("hh");
ud.getAddr().add(homead);
ud.getAddr().add(officead);
SessionFactory sf;
ServiceRegistry sr;
Configuration cfg=new Configuration().configure();
sr=new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
sf=cfg.buildSessionFactory(sr);
Session s=sf.openSession();
s.beginTransaction();
s.save(ud);
s.getTransaction().commit();
s.close();
ud=null;
s=sf.openSession();
//if type is lazy it returns only the variables of that class no more reference variables.
//if type is Eager it returns all the elements of user class
ud=(UserDetails)s.get(UserDetails.class, 1);
System.out.println(ud.getAddr().size());
}
}
Model class:-
#Entity
public class UserDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int UserId;
private String UserName;
#ElementCollection(fetch=FetchType.EAGER)
#JoinTable(name="User_Address",joinColumns=#JoinColumn(name="User_Id"))
#GenericGenerator(name="hilo-gen" ,strategy="hilo")
#CollectionId(columns={#Column(name="AddressId")},generator="hilo-gen",type=#Type(type="long"))
private Collection<Address> addr=new ArrayList<Address>();
public Collection<Address> getAddr() {
return addr;
}
public void setAddr(Collection<Address> addr) {
this.addr = addr;
}
public int getUserId() {
return UserId;
}
public void setUserId(int userId) {
UserId = userId;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
}
Address class is here :-
#Embeddable
public class Address {
#Column(name="Office_name")
private String House;
public String getHouse() {
return House;
}
public void setHouse(String house) {
House = house;
}
public String getStreet() {
return Street;
}
public void setStreet(String street) {
Street = street;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
#Column(name="street_name")
private String Street;
#Column(name="city_name")
private String City;
#Column(name="state_name")
private String State;
#Column(name="country_name")
private String Country;
}
when i try to run my code there is no error from hibernate but an mysql error is encountered I am new to mysql can anyone explain me in deatil the cause of this error and how to fix it.
thanks in advance
I am just not getting the point here. Whats going on with the following code, where is the error? I have to Classes: Ressource and Reservation. A Resource can have multiple Reserverations and the relation is bidirectional. To me, eveything seems find and I have looked at a bunch ressources and documentations - ah yep, also at a lot of examples and I cant get to the rootcause of this.
Any body of you gets the issue, or could somebody at least tell me that nothing is wrong with it:)
package org.ademi.model;
import java.io.Serializable;
import java.util.Calendar;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.Entity;
#Entity
#Table(name="Ressource")
public class Ressource implements Serializable{
private static final long serialVersionUID = 12L;
/**
* A Ressource is available from a specific Date.
*/
private Calendar availableFrom;
/**
* A Ressource is available until specific Date.
*/
private Calendar availableTo;
/**
* This is a unique Ressource ID.
*/
private int id;
/**
* A set of reservations that belong to this ressource
*/
private List<Reservation> reservations;
/**
* A list of Days, when the ressource is available
*/
private List<Day> daysAvailable;
/**
* This is specifying the intervall aloud for the reservation;
*/
private Intervall intervall;
/**
* Type of the ressource
*/
private String type;
/**
* Name of the ressource
*/
private String name;
public Ressource(String name, String type, Calendar availableFrom, Calendar availableto, List<Day> daysAvailable, Intervall intervall){
this.availableFrom = availableFrom;
this.availableTo = availableto;
this.daysAvailable = daysAvailable;
}
#Temporal(TemporalType.DATE)
public Calendar getAvailableFrom() {
return availableFrom;
}
public void setAvailableFrom(Calendar availableFrom) {
this.availableFrom = availableFrom;
}
#Temporal(TemporalType.DATE)
public Calendar getAvailableTo() {
return availableTo;
}
public void setAvailableTo(Calendar availableTo) {
this.availableTo = availableTo;
}
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#OneToMany(mappedBy="Reservation",cascade = CascadeType.ALL)
public List<Reservation> getReservations() {
return reservations;
}
public void setReservations(List<Reservation> reservations) {
this.reservations = reservations;
}
#Enumerated(EnumType.STRING)
public Intervall getIntervall() {
return intervall;
}
public void setIntervall(Intervall intervall) {
this.intervall = intervall;
}
#ElementCollection(targetClass=Day.class)
#Enumerated(EnumType.STRING)
#CollectionTable(name="daysAvailable")
#Column(name="daysAvailable")
public List<Day> getDaysAvailable() {
return daysAvailable;
}
public void setDaysAvailable(List<Day> daysAvailable) {
this.daysAvailable = daysAvailable;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package org.ademi.model;
import java.io.Serializable;
import java.util.Calendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="Reservation")
public class Reservation implements Serializable{
private static final long serialVersionUID = 1L;
/**
* A unique ID belonging to a reservation.
*/
private int id;
/**
* Timesstamp for the beginning of the reservation
*/
private Calendar reservationStarts;
/**
* Amount of Intervalls for the reservation
*/
private int reservedIntervalls;
/**
* A short summary Title describing the reservation
*/
private String title;
/**
* The resource which is reserved in this reservation.
*/
private Ressource ressource;
public Reservation(String title, Ressource ressource, Calendar reservationStarts, int reservedIntervalls){
this.title = title;
this.ressource = ressource;
this.reservationStarts = reservationStarts;
this.reservedIntervalls = reservedIntervalls;
}
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Temporal(TemporalType.TIMESTAMP)
public Calendar getReservationStarts() {
return reservationStarts;
}
public void setReservationStarts(Calendar reservationStarts) {
this.reservationStarts = reservationStarts;
}
public int getReservedIntervalls() {
return reservedIntervalls;
}
public void setReservedIntervalls(int reservedIntervalls) {
this.reservedIntervalls = reservedIntervalls;
}
#ManyToOne
#JoinColumn(name="ressource_ID")
public Ressource getRessource() {
return ressource;
}
public void setRessource(Ressource ressource) {
this.ressource = ressource;
}
}
My persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<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_1_0.xsd"
version="1.0">
<persistence-unit name="iplandb">
<properties>
<!--
<property name="hibernate.ejb.cfgfile" value="/hibernate.cfg.xml"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
-->
<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="kbausbes"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/iplandb"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="3000"/>
</properties>
</persistence-unit>
</persistence>
A simple TestingClass
package org.ademi.client;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.ademi.model.Day;
import org.ademi.model.Intervall;
import org.ademi.model.Ressource;
public class TestClient {
public static void main(String[] args){
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("iplandb");
/* Create EntityManager */
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
ArrayList<Day> a = new ArrayList<Day>();
a.add(Day.FRIDAY);
Ressource r = new Ressource("ilir", "ademi", new GregorianCalendar(), new GregorianCalendar(),a, Intervall.EIGHT );
em.persist(r);
em.flush();
}
}
And this is the Exceptions I am getting:
Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: iplandb] Unable to configure EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:265)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:125)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:52)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:34)
at org.ademi.client.TestClient.main(TestClient.java:20)
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on org.ademi.model.Reservation.ressource references an unknown entity: org.ademi.model.Ressource
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:81)
at org.hibernate.cfg.AnnotationConfiguration.processEndOfQueue(AnnotationConfiguration.java:456)
at org.hibernate.cfg.AnnotationConfiguration.processFkSecondPassInOrder(AnnotationConfiguration.java:438)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:309)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1162)
at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1226)
at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:173)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:854)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:191)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:253)
... 4 more
The class is annotated with #org.hibernate.annotations.Entity. It must be annotated with javax.persistence.Entity.
Fix your import.
Another problem is that mappedBy="Reservation" should be mappedBy="ressource". mappedBy contains the name of the property of the target class that is the owner side of the association.
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.