Hibernate mapping exception even though mappings appear correct - java

I've this Java application in package com.luv2code.hibernate.demo:
package com.luv2code.hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.luv2code.hibernate.demo.entity.Employee;
public class CreateEmployeeDemo {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Employee.class)
.buildSessionFactory();
// create a session
Session session = factory.getCurrentSession();
try {
// create the employee object
System.out.println("Creating a new employee object...");
Employee tempEmployee = new Employee("John", "Doe", "Doe Corp.");
// start a transaction
session.beginTransaction();
// save the employee object
System.out.println("Saving the employee...");
session.save(tempEmployee);
// commit the transaction
session.getTransaction().commit();
// find the employee's ID: primary key
System.out.println("Save employee. Generated ID: " + tempEmployee.getId());
// now get a new session and start transaction
session = factory.getCurrentSession();
session.beginTransaction();
// retrieve employee based on the ID: primary key
System.out.println("\nGettin employee with id: " + tempEmployee.getId());
Employee myEmployee = session.get(Employee.class, tempEmployee.getId());
System.out.println("Get complete: " + myEmployee);
// commit the transaction
session.getTransaction().commit();
// delete student id=2
System.out.println("Deleting student id=2");
session.createQuery("delete from Student where id = '2'").executeUpdate();
// commit the transaction
session.getTransaction().commit();
System.out.println("Done!");
}
finally {
factory.close();
}
}
}
It uses this Employee class in package com.luv2code.hibernate.demo.entity:
package com.luv2code.hibernate.demo.entity;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="company")
private String company;
public Employee() {
}
public Employee(String firstName, String lastName, String company) {
this.firstName = firstName;
this.lastName = lastName;
this.company = company;
}
public int getId() {
return id;
}
public void setId(int 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 String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
#Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", company=" + company + "]";
}
}
When I run the program I get this error:
Saving the employee...
Jul 17, 2020 6:46:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PoolState stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC]
Jul 17, 2020 6:46:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections close
ERROR: Connection leak detected: there are 1 unclosed connections upon shutting down pool jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.luv2code.hibernate.demo.entity.Employee
at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:704)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1606)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:114)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:179)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:75)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:634)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:627)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:622)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:351)
at com.sun.proxy.$Proxy25.save(Unknown Source)
at com.luv2code.hibernate.demo.CreateEmployeeDemo.main(CreateEmployeeDemo.java:33)
I can't see what could be wrong here. It seems to be a mapping exception but I think my mappings should be correct. Can anybody spot the issue?

Use #Entity and #Table for map database table name with Employee class
#Entity
#Table(name = "employee")
public class Employee { ... }

Related

Error : org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

I am getting error when i run application.
This Is My Simple Hibernate Application.
When I Run My Application Is Eclipse IDE It Gives Me Error.
Error : org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
I Get This Error When I Run My Application.
This Is My Student Class.
Student.java
package com.nikunj.hibernate.demo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
#Id
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
public Student() {
// super();
}
public Student(String firstName, String lastName, String email) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int 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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
This Is My Hibernate Configuration XML File.
hibernate.cfg.xml
<!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>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC</property>
<property name="connection.username">hbstudent</property>
<property name="connection.password">hbstudent</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
This Is My Main Class.
CreateStudentDemo.java
package com.nikunj.hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.nikunj.hibernate.demo.entity.Student;
public class CreateStudentDemo {
public static void main(String[] args) {
try {
// Create session factory
SessionFactory factory = new Configuration().configure().addAnnotatedClass(Student.class)
.buildSessionFactory();
// Use the session object to save Java object
Session session = factory.getCurrentSession();
// Create a student object
System.out.println("Creating new student object...");
Student tempStudent = new Student("Nikunj", "Rathva", "Nikunjrathva108#gmail.com");
// Start a transaction
session.beginTransaction();
// Save the student object
System.out.println("Saving the student...");
session.save(tempStudent);
// Commit transaction
session.getTransaction().commit();
System.out.println("Done!");
factory.close();
} catch (Exception e) {
System.out.println("\n\n\nError : " + e + "\n\n\n");
e.printStackTrace();
}
}
}
```[Jar Files For Hibernate ORM][1]
[1]: https://i.stack.imgur.com/6iORy.png

TypeMisMatchException in hibernate

Following is my Person class:
package com.subir.sample;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name ="person",uniqueConstraints = {#UniqueConstraint(columnNames= {"NAME"})})
public class Person implements Serializable{
/**
*
*/
private static final long serialVersionUID = -2728179031744032393L;
int age;
String name;
char isVip;
public Person() {
}
public Person(int age, String name, char isVip) {
this.age = age;
this.name = name;
this.isVip = isVip;
}
#Id
#Column(name="AGE")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Id
#Column(name="NAME")
//#OneToMany(mappedBy="NAME")
private Set <Subject> subjects;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Id
#Column(name="ISVIP")
public char getIsVip() {
return isVip;
}
public void setIsVip(char isVip) {
this.isVip = isVip;
}
}
And the following is my class for add and view persons.
package com.subir.sample;
import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class PersonDbAccess {
public static void addPerson(String name, int age, char isVip, Session session, org.hibernate.Transaction tx) {
try {
tx = session.beginTransaction();
Person p = new Person(age, name, isVip);
session.save(p);
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public static void viewPerson(String name, Session session) {
try {
System.out.println("Name value in view method is :: " + name);
Person person = (Person)session.get(Person.class, name);
System.out.println("Person.class is ::" + Person.class + " Person.class.getName is :: "
+ Person.class.getName() + " Person.class.getSimpleName() is :: " + Person.class.getSimpleName()
+ " Person.class.getCanonicalName is :: " + Person.class.getCanonicalName());
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
public static void main(String[] args) {
SessionFactory factory = HibernateUtils.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
String name = "Subir";
int age = 20;
char isVip = 'Y';
// addPerson(name,age,isVip,session,tx);
viewPerson("Subir", session);
}
}
And following is my stacktrace:
Exception in thread "main" org.hibernate.TypeMismatchException: Provided id of the wrong type for class com.subir.sample.Person. Expected: class com.subir.sample.Person, got class java.lang.String
at org.hibernate.event.internal.DefaultLoadEventListener.checkIdClass(DefaultLoadEventListener.java:166)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:86)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1240)
at org.hibernate.internal.SessionImpl.access$1900(SessionImpl.java:204)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.doLoad(SessionImpl.java:2842)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2816)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:1076)
at com.subir.sample.PersonDbAccess.main(PersonDbAccess.java:53)
Even though, I am passing object.class,String in the get method of the session object, it is giving me type mismatch exception.
You need to pass the ID to your hibernate session get method. In your case you have a compound key , fetching only by name might result in more than one object being returned which contradicts with the nature of the get operation which returns a single object by primary key.
You need to use a Criteria or Query here.
On another note if you want to use the Session.get method, instead of marking multiple columns with ID which is not JPA complient you should create an EmbededId and use it in the Session.get method. Then it will not incompatible type.
Read https://vladmihalcea.com/the-best-way-to-map-a-composite-primary-key-with-jpa-and-hibernate/
UPDATE:
I can see you have Unique constraint on name. Why do you need the AGE and the isVip to be part of your key , because marking them with ID you are effectivly making them part of your key.

Unable to update a record via Hibernate

I am able to successfully create and insert entries in a table via Hibernate, however for some reason my update method appears to not be working.
For my table, I chose to use Java annotations in the POJO file to create it.
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
*
* #author
*/
#Entity
#Table(name="student") //name of DB table that will be created via Hibernate
public class Student {
#Id //Primary Key
#Column(name = "id") //map to column
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "marks")
private Integer marks;
public Student(Integer id, String name, Integer marks) {
this.id = id;
this.name = name;
this.marks = marks;
}
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 getMarks(){
return marks;
}
public void setMarks(Integer marks) {
this.marks = marks;
}
#Override
public String toString() {
return "Student: " + this.getId() + " | " + this.getName() + " | " + this.getMarks();
}
}
As aforementioned, the table is successfully created in a MySQL database. However, I am unable to update an objects Marks (grade) via my HQL query:
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
*
* #author
*/
public class HibernateModuleTen {
private static SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
public static void main(String[] args) {
Session newSession = factory.getCurrentSession();
try {
/*Create Student Objects
in Memory
*/
Student student1 = new Student(100, "Greg", 95);
Student student2 = new Student(101, "Mary", 91);
Student student3 = new Student(102, "Sidi", 90);
Student student4 = new Student(103, "Rokia", 92);
Student student5 = new Student(104, "Abdel", 88);
Student student6 = new Student(105, "Christine", 77);
Student student7 = new Student(106, "Hamma", 90);
Student student8 = new Student(107, "Ahmadu", 68);
Student student9 = new Student(108, "Halimatu", 96);
Student student10 = new Student(109, "Iziren", 99);
//Begin transaction
newSession.beginTransaction();
//Save all the students
newSession.save(student1);
newSession.save(student2);
newSession.save(student3);
newSession.save(student4);
newSession.save(student5);
newSession.save(student6);
newSession.save(student7);
newSession.save(student8);
newSession.save(student9);
newSession.save(student10);
newSession.getTransaction().commit();
//Update a Student Record
updateStudent(107, 34);
//Delete a record if marks are less than 35 and then update Database
deleteStudent();
//Print all records
newSession = factory.openSession();
newSession.beginTransaction();
Criteria newCriteria = newSession.createCriteria(Student.class);
List<Student> students = newSession.createQuery("from Student").list(); //.list is .getResultList in later versions of Hibernate
for (Student aStudent : students) {
System.out.println(aStudent.toString());
}
newSession.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
factory.close();
}
}
public static void updateStudent(Integer id, Integer marks) throws HibernateException {
/*Update Transaction*/
Session newSession = factory.openSession();
newSession.beginTransaction();
Student studentToUpdate = (Student)newSession.get(Student.class, id); //Choose record 107 to update
//Update the marks of Student based on ID and marks
studentToUpdate.setMarks(marks);
newSession.update(studentToUpdate);
//Commit to the Transaction
newSession.getTransaction().commit();
newSession.close();
}
public static void deleteStudent() throws HibernateException {
Session newSession = factory.openSession();
newSession.beginTransaction();
newSession.createQuery("delete from student s where smarks < 35")
.executeUpdate(); //Used for updates and deletes
newSession.getTransaction().commit();
newSession.close();
}
}
The update method effectively takes one of the records in the table via the id column and updates the element in the marks column.
There was an issue with my delete method:
public static void deleteStudent() throws HibernateException {
Session newSession = factory.openSession();
newSession.beginTransaction();
newSession.createQuery("delete from student s where smarks < 35")
.executeUpdate(); //Used for updates and deletes
newSession.getTransaction().commit();
newSession.close();
}
If one looks closely at the query, the "delete from student" should be "delete from Student" with a capital s. Careless error.
You didn't post your errors here, but looks like your Student bean class doesn't have a default constructor which is being invoked while executing
Student studentToUpdate = (Student)newSession.get(Student.class, id);
You can try after adding a default constructor to Student class along with your custom constructor.

How to save multiple objects via ArrayList in hibernate?

I have a Student entity. My idea is to collect multiple student objects in an ArrayList and save all objects from that list to the database. When do you use #ElementCollection annotation? Does it apply to situations like this?
Student:
package basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
public Student() {
}
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;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
public Student(String name) {
this.name = name;
}
}
Runner:
package basic;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Runner {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure("/basic/hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
List<Student> students = new ArrayList<>();
students.add(new Student("Michael"));
students.add(new Student("Dave"));
students.add(new Student("Tom"));
students.add(new Student("Dinesh"));
students.add(new Student("Lakshman"));
students.add(new Student("Cruise"));
session.save(students);
session.getTransaction().commit();
session.close();
}
}
Error
Exception in thread "main" org.hibernate.MappingException: Unknown entity: java.util.ArrayList
at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1596)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:668)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:660)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:655)
at basic.Runner.main(Runner.java:27)
You have to do something like this:
for(Student student : students) {
session.save(student);
}
If you want to save entity you should map it. ArrayList<> is not mapped entity. Student has mapping so you should save it separately.
#ElementCollection you should use to define relation between object - here you have nice explenation https://en.wikibooks.org/wiki/Java_Persistence/ElementCollection
To save list of object, you need to iterate by objects, something like this -> How to insert multiple rows into database using hibernate?
I would further recommend to use another Hibernate command to avoid an Out Of Memory error...
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
for (int i = 0 ; i < students.size(); i++) {
session.save(students.get(i));
if (i % 100 == 0) {//a batch size for safety
session.flush();
session.clear();
}
}
transaction.commit();
session.close();
sessionFactory.close();

Table 'customerjpa.sequence' doesn't exist JPA

I am facing following problem while inserting data into table using single inheritance in jpa.
run:
[EL Info]: 2014-04-17 22:40:45.947--ServerSession(863001717)--EclipseLink, version: Eclipse Persistence Services - 2.2.0.v20110202-r8913
[EL Info]: 2014-04-17 22:40:46.387--ServerSession(863001717)--file:/C:/Users/xone/Documents/NetBeansProjects/JPAAditiDAS/build/classes/_TESTJPAPU login successful
[EL Warning]: 2014-04-17 22:40:46.469--ClientSession(1037426453)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'customerjpa.sequence' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
Exception in thread "main" Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'customerjpa.sequence' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:798)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:864)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:583)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:526)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1729)
at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:234)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:207)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:193)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeNoSelectCall(DatasourceCallQueryMechanism.java:236)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeNoSelect(DatasourceCallQueryMechanism.java:216)
at org.eclipse.persistence.queries.DataModifyQuery.executeDatabaseQuery(DataModifyQuery.java:85)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:808)
at org.eclipse.persistence.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:2800)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1521)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1503)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1477)
at org.eclipse.persistence.sequencing.QuerySequence.update(QuerySequence.java:336)
at org.eclipse.persistence.sequencing.QuerySequence.updateAndSelectSequence(QuerySequence.java:275)
at org.eclipse.persistence.sequencing.StandardSequence.getGeneratedVector(StandardSequence.java:71)
at org.eclipse.persistence.sequencing.DefaultSequence.getGeneratedVector(DefaultSequence.java:163)
at org.eclipse.persistence.sequencing.Sequence.getGeneratedVector(Sequence.java:257)
at org.eclipse.persistence.internal.sequencing.SequencingManager$Preallocation_Transaction_NoAccessor_State.getNextValue(SequencingManager.java:474)
at org.eclipse.persistence.internal.sequencing.SequencingManager.getNextValue(SequencingManager.java:961)
at org.eclipse.persistence.internal.sequencing.ClientSessionSequencing.getNextValue(ClientSessionSequencing.java:70)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:292)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.assignSequenceNumber(UnitOfWorkImpl.java:454)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4190)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:493)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4135)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:406)
at test.SingleInheritenceCustTest.main(SingleInheritenceCustTest.java:35)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'customerjpa.sequence' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2794)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:789)
... 30 more
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
Main Class:
package test;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import entity.CustomerSingle;
import entity.OnlineCustomer;
/*
* This is a test class for testing Single table inheritance
*/
public class SingleInheritenceCustTest {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("TESTJPAPU");
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
//inserting Customer
CustomerSingle customer = new CustomerSingle();
customer.setFirstName("Antony");
customer.setLastName("John");
customer.setCustType("RETAIL");
customer.getAddress().setStreet("1 Broad street");
customer.getAddress().setAppt("111");
customer.getAddress().setCity("NewYork");
customer.getAddress().setZipCode("23456");
em.persist(customer);
inserting Online Customer
OnlineCustomer onlineCust = new OnlineCustomer();
onlineCust.setFirstName("Henry");
onlineCust.setLastName("Ho");
onlineCust.setCustType("ONLINE");
onlineCust.getAddress().setStreet("1 Mission Street");
onlineCust.getAddress().setAppt("222");
onlineCust.getAddress().setCity("Seatle");
onlineCust.getAddress().setZipCode("33345");
onlineCust.setWebsite("www.amazon.com");
em.persist(onlineCust);
userTransaction.commit();
// fetch only the online customers
/*Query query = em.createQuery("SELECT customer FROM ONLINECUSTOMER customer");
List<OnlineCustomer> list= query.getResultList();
System.out.println("The list is: "+ list);
for(int i=0;i<list.size();i++){
System.out.println("ONLINE CUSTOMER ["+ i +"] " + list.get(i));
}*/
em.close();
entityManagerFactory.close();
}
}
Entity Class CustomerSingle:
It contains common features of customer. It is used to insert data by using discrimination value "RETAIL"
package entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/*
* CUSTOMER ENTITY CLASS -> This is an example of Single table inheritance
*/
#Table(name="CUSTOMER")
#Entity(name = "CUSTOMER2") //Name of the entity
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name="CUST_TYPE", discriminatorType=DiscriminatorType.STRING,length=10)
#DiscriminatorValue("RETAIL")
public class CustomerSingle implements Serializable{
#Id //signifies the primary key
#Column(name = "CUST_ID", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private long custId;
#Column(name = "FIRST_NAME", nullable = false,length = 50)
private String firstName;
#Column(name = "LAST_NAME", length = 50)
private String lastName;
#Embedded
private Address address = new Address();
#Column(name = "CUST_TYPE", length = 10)
private String custType;
#Column(name = "LAST_UPDATED_TIME")
#Temporal(TemporalType.TIMESTAMP)
private Date updatedTime;
public long getCustId() {
return custId;
}
public void setCustId(long custId) {
this.custId = custId;
}
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 Date getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getCustType() {
return custType;
}
public void setCustType(String custType) {
this.custType = custType;
}
//
ToString()
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("custId : " + custId);
sb.append(" First Name : " + firstName);
sb.append(" Last Name : " + lastName);
sb.append(" customer type : " + custType);
return sb.toString();
}
}
ONLINECUSTOMER is an another entity class which extends CUSTOMERSINGLE. It is used to insert data by usinf discrimination value "ONLINE"
package entity;
import javax.persistence.*;
/*
* ONLINE CUSTOMER ENTITY CLASS -> This is an example of Single table inheritance
*/
#Entity(name = "ONLINECUSTOMER") //Name of the entity
#DiscriminatorValue("ONLINE")
public class OnlineCustomer extends CustomerSingle{
#Column(name = "WEBSITE", length = 100)
private String website;
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(super.toString());
sb.append(" website: "+website);
return sb.toString();
}
}
The exception is caused due to a missing sequence table in the underlying database:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
Table 'customerjpa.sequence' doesn't exist
There are two solutions depending on the configuration:
Let EclipseLink do it for you by specifying eclipselink.ddl-generation in pesistence.xml. (preferred)
Create sequence manually by executing SQL statement.

Categories

Resources