I am having a problem with hibernate. I am updating a previously created database created in Oracle SQL in order to get some practice with hibernate. The thing is that I am getting an AnnotationException that one class object is trying to reference something from the other class. Here is the error:
org.hibernate.AnnotationException: #OneToOne or #ManyToOne on com.revature.bank.POJO.BankAccount.customer references an unknown entity: com.revature.bank.POJO.Customer
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:107)
at org.hibernate.cfg.Configuration.processEndOfQueue(Configuration.java:1580)
at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1503)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1419)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1856)
at com.revature.bank.POJO.DataFuncImp.createCustomer(DataFuncImp.java:16)
at com.revature.bank.POJO.Main.main(Main.java:9)
So, this is pointing to the line:
SessionFactory sf = new Configuration().configure().buildSessionFactory();
I have read that it might be happening because the annotations but none of the previously asked questions here seemed to work.
Here are my two classes: (i will only put the variables as that's where the error points to):
Customer.java
#Entity
#Table(name="USER_TABLE")
public class Customer {
#Id
#GeneratedValue
private int user_id;
#Column
private String user_fname;
#Column
private String user_lname;
#Column
private String user_email;
#Column
private String user_address;
#Column
private String user_city;
#Column
private String user_state;
#Column
private long cell_num;
#OneToMany(cascade= {CascadeType.ALL}, mappedBy="customer")
#JoinColumn(name="user_id")
private List<BankAccount> bacct;
BankAccount.java
#Entity
#Table(name="USER_ACCOUNT")
public class BankAccount {
#Id
#GeneratedValue
private long acct_id;
#Column
private double balance;
#ManyToOne
#JoinColumn(name="user_id")
private Customer customer;
And here is my hibernate config file as well(edited out the database connection info):
<?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.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">adminone</property>
<property name="hibernate.connection.password">adminpass</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle11gDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> -->
<!-- <mapping resource="students.hbm.xml"></mapping> -->
<mapping class="com.revature.bank.POJO.Customer"></mapping>
<mapping class="com.revature.bank.POJO.BankAccount"></mapping>
</session-factory>
</hibernate-configuration>
I am using hibernate 3.0. Like i mentioned earlier, i have been trying to figure out the error but none of the online help seemed to fix it. As you can see, I'm not even trying to do anything to the database yet and it is throwing that exception. Any idea on why is this happening? Thank you in advance!!
You shouldn't have JoinColumn on both sides. Just on the owner side, so remove it from the Customer class.
Customer.java:
#OneToMany(cascade= {CascadeType.ALL}, mappedBy="customer")
private List<BankAccount> bacct;
BankAccount.java:
#ManyToOne
#JoinColumn(name="user_id")
private Customer customer;
Related
I am getting strange error Caused by:
java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint
While executing my below code:
Product DAO.java
#Id
#Column(name = "no", columnDefinition = "NUMBER")
private int serial_number;
//No getter and setter for this field
#Column(name = "fname", columnDefinition = "VARCHAR2(50)")
private int fname;
#Column(name = "lname", columnDefinition = "VARCHAR2(50)")
private int lname;
// Getter and setter for fname and lname
ProductService.java
Product po = new Product();
po.setfname = "Tom";
po.setlname = "John";
//I am not setting 'no' field value since I have created sequence in my oracle table to auto increment the value.
When I am running this code, I am getting unique constraint error on field 'no'. Can anyone help me in identifying what I am doing wrong in my code. When I have already created sequence for 'no' field in my table, do I need to make any change in config file or code? Since its the production database, I do not know the sequence name also.
hibernate-cgf.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.password">pass</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="dao.Product"></mapping>
</session-factory>
</hibernate-configuration>
Your id field serial_number is an int which is initialized to zero, and your mapping for #Id does not include a #GeneratedValue annotation, so hibernate will assume you are assigning the id manually and save it as zero every time you persist an object, causing the SQLIntegrityConstraintViolationException. You need to add a #GeneratedValue annotation and you can also choose a strategy, like this:
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "no", columnDefinition = "NUMBER")
private int serial_number;
I have 2 projects:
1 for the entities
1 for a web service
While using Hibernate 4.3.11.Final everything was working properly. I have a hibernate.cfg.xml where I have all the classes so selecting the entities from the DB was ok using Query
Then I changed to Hibernate 5.2.6.Final and I had to change Query for TypedQuery<Entity> and now it complains that the entity is not mapped.
A test I made calls this code.
TypedQuery<Employee> query = getSession().createQuery(
"SELECT e from Employee e where e.username = :username");
query.setParameter("username", employee.getUsername());
return query.getSingleResult();
And it complains that the entity I'm selecting in the query "SELECT e from Employee..." (not the one defined in the TypedQuery) is the one that's not mapped.
Is there a new way to map the entities in 5.2.6? How could I solve this?
The Employee entity:
#Entity
#Table(name = "employee")
#XmlRootElement
public class Employee implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Long id;
#Basic(optional = false)
#Column(name = "username")
private String username;
// Getters & Setters...
}
The entry in the hibernate.cfg.xml file is like this:
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/db</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">pass</property>
<mapping class="com.entities.Employee"/>
<mapping class="all other entities"/>
If I change the dependency back from 5.2.6.Final to 4.3.11.Final
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.11.Final</version>
</dependency>
I have no problem and everything works as it should be.
I have a Role object which holds several permissions(which are ENUM).
But i keep getting this error.
Use of #OneToMany or #ManyToMany targeting an unmapped class: objects.Role.permissions[enums.AgentPermission]
What is the best way to represent.
Role Class:
#Entity
#Table(name="\"Role\"")
public class Role {
#Id
#GeneratedValue
private int id;
#ManyToOne
private Company company;
private String name;
#ManyToMany
private Set<AgentPermission> permissions;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
....
}
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>
<!-- hibernate dialect -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
....
<mapping class="objects.Role" />
<mapping class="objects.Tag" />
....
</session-factory>
</hibernate-configuration>
Try #ElementCollection on your Set of permissions.
I am trying to make a relationship between 2 entities in different jar.
This is a first entity which is in main project:
#Entity(name = "StdyDtlLabelBean")
#Table(name = "STDY_DTL_LABEL")
public class StdyDtlLabelBean implements Serializable {
#EmbeddedId
private StdyDtlLabelBeanPk id;
#ManyToOne(targetEntity = StdyDtlSubject.class)
#JoinColumns({
#JoinColumn(name="STUDY_ID", insertable = false, updatable = false, referencedColumnName="STUDY_ID"),
#JoinColumn(name="SUBJECT_ID", insertable = false, updatable = false, referencedColumnName="SUBJECT_ID")
})
private StdyDtlSubject subject;
//getters and setters
}
This one is an entity which is in library project as a jar file:
#Entity
#Table(name = "STDY_DTL_SUBJECT")
public class StdyDtlSubject implements Serializable {
private static final long serialVersionUID = 2479124604L;
public StdyDtlSubject() {
}
#EmbeddedId
private StdyDtlSubjectPK key;
//getters and setters
}
#Embeddable
public class StdyDtlSubjectPK implements Serializable {
private static final long serialVersionUID = 6691432687933341920L;
#Column(name = "STUDY_ID")
private Integer studyId;
#Column(name = "SUBJECT_ID")
private String subjectId;
public StdyDtlSubjectPK() {
}
Here is the persistence unit:
<persistence-unit name="stdyPersistence" transaction-type="RESOURCE_LOCAL">
<jta-data-source>java:comp/env/jdbc/OraclePooledDS</jta-data-source>
<class>com.ctasc.ctpm.jpa.StdyDtlSubject</class>
<class>stdy.brms.beans.StdyDtlLabelBean</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
When I create an entity manager factory I gets following error:
#OneToOne or #ManyToOne on stdy.brms.beans.StdyDtlLabelBean.subject references an unknown entity: com.ctasc.ctpm.jpa.StdyDtlSubject
But if I remove a relationship annotation from StdyDtlLabelBean entity and create named queries on StdyDtlSubject entity. Those named queries work fine. Also, if I copy StdyDtlSubject class to my main project, it works fine. I gets this error only if I put relationship between them.
I've tried adding
<jar-file>ctpm.jar</jar-file>
<jar-file>lib/ctpm.jar</jar-file>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<property name="hibernate.archive.autodetection" value="class, hbm" />
<property name="packagesToScan" value="com.ctasc.ctpm.jpa" />
None of them helped me to solve this. Could you please suggest something to solve this problem?
Ensure that the jar which you want to relate to has a persisence.xml in it's META-INF with all entities in the jar enlisted.
I'm trying to setup JPA with a hibernate implementation for the first time with this test project. Ran into the following error:
Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: ExamModulePu] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:924)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:59)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at service.tests.ExamServiceTest.main(ExamServiceTest.java:18)
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on entities.Question.examId references an unknown entity: long
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:109)
at org.hibernate.cfg.Configuration.processEndOfQueue(Configuration.java:1536)
at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1457)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1365)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
These are my entities:
#Entity
public class Exam implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private int numQuestions;
private int minutesAllotted;
private Date startDate;
private Date endDate;
#OneToMany(mappedBy = "examId", orphanRemoval = true)
private List<Question> questionList;
// Getters and setters here..
}
#Entity
public class Question implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
#ManyToOne
private long examId;
private int points;
private int timeLimit;
private String text;
private String category;
#Embedded
private List<Answer> answerList;
}
#Embeddable
public class Answer implements Serializable {
private int optionNumber;
private String text;
private boolean correct;
}
This is what my persistence.xml looks like:
<?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_2_0.xsd"
version="2.0">
<persistence-unit name="ExamModulePu"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>entities.Exam</class>
<class>entities.Question</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/exammoduledb" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
</persistence-unit>
</persistence>
I haven't created any of the tables, but instead am depending on the hibernate.hb2mddl.auto to do so. But I believe my error springs up even before that happens as it can't generate the persistence unit. Any ideas what I'm doing wrong? I'm making sure I import only javax.persistence.*;
If you look closely at your stacktrace, you will see
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on entities.Question.examId references an unknown entity: long
So this field
#ManyToOne
private long examId;
is causing the problem. #ManyToOne has a paramater targetEntity which says:
(Optional) The entity class that is the target of the association.
Defaults to the type of the field or property that stores the association.
Since you haven't provided that parameter, it defaults to long, which is not a managed Entity.
You'll probably want to use
#ManyToOne(targetEntity = Exam.class)
private long examId;
otherwise it won't know what to map to. Or even better
#ManyToOne
private Exam exam;
Just add the class Team to the "hibernate-cfg.xml" file, because Hibernate doesn't identify without adding into it.
FYI, this sometimes happens if you have a hibernate annotation:
#org.hibernate.annotations.Entity
and a JPA annotation:
#javax.persistence.Entity
mixed up
Edit:
Explicitly import the javax annotation.
It took me hours to find the actual issue
I had forgotten the #Entity annotation on the Parent class and the error use to show on the child class.
In my case Hibernate was not able to identify the entity because I had not added that entity in sessionfactory using .addAnnotatedClass(XYZ.class) so it was not able to find that particular entity.