I am trying to implement inheritance using hibernate and using simple program
Well I am declaring a class of person having four attributes-age,sex,name,id(which is auto generated)
Now I have two classes inheriting the base class
The first class is native where one attribute is there that defines pincode whereas the other class is foreign where psotcode is defined
Following is my whole code
person.java
package com;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Person {
private String Name;
private int age;
private String sex;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String id;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
native.java
package com;
import javax.persistence.Entity;
#Entity
public class Native extends Person {
private int pincode;
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
}
foreign.java
package com;
import javax.persistence.Entity;
#Entity
public class Foreign extends Person {
private String postcode;
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
mainclass.java
package com;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class Classmain {
public static void main(String args[])
{
Person person = new Person();
person.setName("krish");
person.setSex("M");
person.setAge(23);
Native native = new Native();
native.setPincode(201545);
native.setAge(23);
native.setName("victor");
native.setSex("M");
Foreign foreign = new Foreign();
foreign.setPostcode("sfadfas0");
foreign.setName("michelle");
foreign.setAge(31);
foreign.setSex("F");
SessionFactory sessionfactory = new AnnotationConfiguration()
.configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
session.save(person);
session.save(foreign);
session.save(native);
session.getTransaction().commit();
session.close();
}
}
Following is my 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/Inherit1</property>
<property name="connection.username">root</property>
<property name="connection.password">vvvvvvvv</property>
<property name="hbm2ddl.auto">update</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" />
<mapping class="com.Native" />
<mapping class="com.Foreign" />
</session-factory>
</hibernate-configuration>
However I am getting the following error
INFO: HHH000232: Schema update complete
Hibernate: insert into Person (Name, age, sex, DTYPE) values (?, ?, ?, 'Person')
Jun 7, 2013 7:12:30 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
Jun 7, 2013 7:12:30 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Table 'Inherit1.Person' doesn't exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:136)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2975)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3487)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:377)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:214)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:194)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:178)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:321)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:206)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:764)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:756)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:752)
at com.Classmain.main(Classmain.java:33)
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'Inherit1.Person' doesn't exist
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1604)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1519)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1504)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)
... 22 more
What could be the reason?
OK, I found your error, but you should have seen in your logs the previous errors:
ERROR: HHH000389: Unsuccessful: create table Person (DTYPE varchar(31) not null, id varchar(255) not null auto_increment, Name varchar(255), age integer not null, sex varchar(255), pincode integer, postcode varchar(255), primary key (id))
07-jun-2013 17:17:35 org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: Incorrect column specifier for column 'id'
If you look at the definition of id, you are trying to declare an auto-increment field with a String variable in Person class. Change it with int and it will work perfectly.
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
A unique table named Person is created and data are inserted correctly.
Try to add #Table(name="table_name") annotations to inherited entities.
Related
I have created a project with SQL Server which the files:
UserDAO.java*
public class UserDAO
{
private static SessionFactory sessionFactory;
static
{
sessionFactory = HibernateUtility.getSessionFactory();
}
#SuppressWarnings("unchecked")
public static List<User> findAll()
{
Session session = sessionFactory.openSession();
Criteria crit = session.createCriteria(User.class);
List<User> userList = crit.list();
return userList;
}
}
UserService.java
public class UserService
{
public static void main(String[] args)
{
List<User> listUsers = UserDAO.findAll();
for(User u : listUsers)
{
System.out.println("User is = " + u.getUserName());
}
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</property>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;database=happy</property>
<property name="hibernate.connection.username">lm</property>
<property name="hibernate.connection.password">pp</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<mapping class="com.annotation.day1.entity.User"/>
</session-factory>
</hibernate-configuration>
After running the project, the exception bellow displayed:
Hibernate:
select
this_.id as id1_0_0_,
this_.password as password2_0_0_,
this_.userName as userName3_0_0_
from
User this_
Aug 07, 2016 9:29:00 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 156, SQLState: S0001
Aug 07, 2016 9:29:00 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Incorrect syntax near the keyword 'User'.
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:89)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2065)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:909)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1682)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)
at com.annotation.day1.dao.UserDAO.findAll(UserDAO.java:74)
at com.annotation.day1.service.UserService.main(UserService.java:24)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'User'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197)
Any help is appreciated. Thanks in advance.
USER is a Reserve Word and needs to be escaped in query using square bracket [] while querying.
If you are using annotations, escape through single quotes. '', like below
#Table(name="`user`")
Also refer here for similar issue.
Faced pretty similar issue, when Column name value has space in between.
Note : Hibernate 5.3.7 with SQLServer 2014
#Entity
#Table(name = "TableName")
public class Customer {
#Id
#Column(name = "cid")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int customerId;
#Column(name = "Customer Name")
private String customerName;
---
---
ERROR:
Solution 1 : Template Literals
Solution 2:
-We could remove the space or add '_' in between
#Column(name = "CustomerName") or #Column(name = "Customer_Name")
Note: Name is also a reserved word in SQLServer.
This is my first Hibernate Application Program. I got this error when executing the main class.I Am trying to insert new record at the table student. Also it is good to say that hibernate doing the connection to the database without any problem !I keep getting this MappingException:
Hibernate: drop table if exists student
Hibernate: create table student (student_id integer not null auto_increment, First_Name varchar(255), Last_Name varchar(255), Age integer, primary key (student_id))
Dec 22, 2015 10:04:44 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Exception in thread "main" org.hibernate.MappingException: Unknown entity: org.hibernate.internal.SessionImpl
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1146)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1358)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:116)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:206)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:683)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:675)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:671)
at biztime.Manager.main(Manager.java:23)
Does anyone have any ideas as I've looked at so many duplicates but the resolutions don't appear to work for me.This is my cfg.xml
My 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>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/anwardb</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
<mapping resource="biztime/student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
My student.java
package biztime;
public class student
{
private int student_id;
private String First_Name;
private String Last_Name;
private int Age;
public int getStudent_id()
{
return student_id;
}
public void setStudent_id(int student_id)
{
this.student_id = student_id;
}
public String getFirst_Name()
{
return First_Name;
}
public void setFirst_Name(String first_Name)
{
First_Name = first_Name;
}
public String getLast_Name()
{
return Last_Name;
}
public void setLast_Name(String last_Name)
{
Last_Name = last_Name;
}
public int getAge()
{
return Age;
}
public void setAge(int age)
{
Age = age;
}
}
student.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="biztime">
<class name="student" table="student ">
<id name="student_id" column="student_id">
<generator class="native"/>
</id>
<property name="First_Name" >
<column name="First_Name"/>
</property>
<property name="Last_Name">
<column name="Last_Name"/>
</property>
<property name="Age">
<column name="Age"/>
</property>
</class>
</hibernate-mapping>
I call it using this main:
Manager.java
package biztime;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Manager
{
public static void main(String[] args)
{
Configuration con=new Configuration();
con.configure();
SessionFactory sf=con.buildSessionFactory();
Session s1=sf.openSession();
student s=new student ();
s.setFirst_Name("hello");
s.setLast_Name("test");
s.setStudent_id(1);
s.setAge(20);
s1.beginTransaction();
s1.save(s1);
s1.getTransaction().commit();
s1.flush();
s1.close();
System.out.println("done");
}
}
You're attempting to save s1 which is a Session. Save s instead, which is a student (and capitalize your classnames).
I don't think you should set student_id, as it is an auto_increment field. Try removing this line: s.setStudent_id(1);
I am geting a #OneToOne reletionship record from database and insert into another database using hibernate but having this error
Hibernate: select appointmen0_.appointmentId as appointm1_13_2_, appointmen0_.appointmentDay as appointm2_13_2_, appointmen0_.appointmentTime as appointm3_13_2_, appointmen0_.doctor_userId as doctor4_13_2_, appointmen0_.patient_patientId as patient5_13_2_, doctor1_.userId as userId2_0_, doctor1_.age as age2_0_, doctor1_.city as city2_0_, doctor1_.cnic as cnic2_0_, doctor1_.contactNumber as contactN5_2_0_, doctor1_.country as country2_0_, doctor1_.email as email2_0_, doctor1_.firstName as firstName2_0_, doctor1_.homeNumber as homeNumber2_0_, doctor1_.houseNo as houseNo2_0_, doctor1_.lastName as lastName2_0_, doctor1_.password as password2_0_, doctor1_.streetNo as streetNo2_0_, doctor1_.town as town2_0_, doctor1_.username as username2_0_, doctor1_.specialization as speciali1_4_0_, patient2_.patientId as patientId5_1_, patient2_.age as age5_1_, patient2_.city as city5_1_, patient2_.cnic as cnic5_1_, patient2_.contactNumber as contactN5_5_1_, patient2_.country as country5_1_, patient2_.email as email5_1_, patient2_.firstName as firstName5_1_, patient2_.homeNumber as homeNumber5_1_, patient2_.houseNo as houseNo5_1_, patient2_.lastName as lastName5_1_, patient2_.password as password5_1_, patient2_.streetNo as streetNo5_1_, patient2_.town as town5_1_, patient2_.username as username5_1_ from AppointmentClass appointmen0_ left outer join Doctor doctor1_ on appointmen0_.doctor_userId=doctor1_.userId left outer join Patient patient2_ on appointmen0_.patient_patientId=patient2_.patientId where appointmen0_.appointmentId=?
Hibernate: insert into Patient (age, city, cnic, contactNumber, country, email, firstName, homeNumber, houseNo, lastName, password, streetNo, town, username, patientId) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into Doctor (age, city, cnic, contactNumber, country, email, firstName, homeNumber, houseNo, lastName, password, specialization, streetNo, town, username, userId) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into Central Appointment (day, doctor_userId, patient_patientId, time, appointmentId) values (?, ?, ?, ?, ?)
org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at com.ehr.admin.services.CentralAppointmentPatientService.transferAppointment(CentralAppointmentPatientService.java:90)
at org.Webapp.admin.CentralizedAppointmentResource.addNewAppointment(CentralizedAppointmentResource.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:143)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:160)
at org.glassfish.jersey.server.model.internal.VoidVoidDispatcherProvider$VoidToVoidDispatcher.doDispatch(VoidVoidDispatcherProvider.java:78)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:97)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:303)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:286)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1072)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:399)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.sql.BatchUpdateException: Batch entry 0 insert into Central Appointment (day, doctor_userId, patient_patientId, time, appointmentId) values ('10', '21', '20', '11', '22') was aborted. Call getNextException to see the cause.
at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2621)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1837)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:407)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2754)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 51 more
My Code is
package com.ehr.admin;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "Central Appointment")
public class CentralAppointment {
#Id
private int appointmentId;
private int day;
private int time;
#OneToOne(fetch = FetchType.EAGER)
private CentralPatient patient;
#OneToOne(fetch = FetchType.EAGER)
private CentralDoctor doctor;
public int getAppointmentId() {
return appointmentId;
}
public void setAppointmentId(int appointmentId) {
this.appointmentId = appointmentId;
}
public CentralPatient getPatient() {
return patient;
}
public void setPatient(CentralPatient patient) {
this.patient = patient;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public CentralDoctor getDoctor() {
return doctor;
}
public void setDoctor(CentralDoctor doctor) {
this.doctor = doctor;
}}
Combine Class of Appointment,Doctor and patient Object:
public class CentralPatientAppointment {
private CentralAppointment appointment;
private CentralPatient patient;
private CentralDoctor doctor;
public CentralAppointment getAppointment() {
return appointment;
}
public void setAppointment(CentralAppointment appointment) {
this.appointment = appointment;
}
public CentralPatient getPatient() {
return patient;
}
public void setPatient(CentralPatient patient) {
this.patient = patient;
}
public CentralDoctor getDoctor() {
return doctor;
}
public void setDoctor(CentralDoctor doctor) {
this.doctor = doctor;
}}
Dao Class:
package com.ehr.admin.services;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.ehr.admin.CentralAppointment;
import com.ehr.admin.CentralDoctor;
import com.ehr.admin.CentralPatient;
import com.ehr.dao.AppointmentPatientService;
import com.ehr.data.AppointmentClass;
public class CentralAppointmentPatientService {
private SessionFactory sessionFactory = null;
public void transferAppointment(){
AppointmentPatientService app = new AppointmentPatientService();
AppointmentClass apt = new AppointmentClass();
apt = app.getParticularPatientAppointment(22);
CentralAppointment cpt = new CentralAppointment();
CentralDoctor doctor = new CentralDoctor();
CentralPatient patient = new CentralPatient();
cpt.setAppointmentId(apt.getAppointmentId());
cpt.setDay(apt.getAppointmentDay());
cpt.setTime(apt.getAppointmentTime());
/**
* Patient Object
*/
patient.setId(apt.getPatient().getId());
patient.setFirstName(apt.getPatient().getFirstName());
patient.setLastName(apt.getPatient().getLastName());
patient.setAge(apt.getPatient().getAge());
patient.setCity(apt.getPatient().getCity());
patient.setCnic(apt.getPatient().getCnic());
patient.setContactNumber(apt.getPatient().getContactNumber());
patient.setCountry(apt.getPatient().getCountry());
patient.setEmail(apt.getPatient().getEmail());
patient.setHomeNumber(apt.getPatient().getHomeNumber());
patient.setHouseNo(apt.getPatient().getHouseNo());
patient.setPassword(apt.getPatient().getPassword());
patient.setStreetNo(apt.getPatient().getStreetNo());
patient.setTown(apt.getPatient().getTown());
patient.setUsername(apt.getPatient().getUsername());
/**
* Doctor Object
*/
doctor.setUserId(apt.getDoctor().getUserId());
doctor.setFirstName(apt.getDoctor().getFirstName());
doctor.setLastName(apt.getDoctor().getLastName());
doctor.setAge(apt.getDoctor().getAge());
doctor.setCity(apt.getDoctor().getCity());
doctor.setCnic(apt.getDoctor().getCnic());
doctor.setContactNumber(apt.getDoctor().getContactNumber());
doctor.setCountry(apt.getDoctor().getCountry());
doctor.setEmail(apt.getDoctor().getEmail());
doctor.setHomeNumber(apt.getDoctor().getHomeNumber());
doctor.setHouseNo(apt.getDoctor().getHouseNo());
doctor.setPassword(apt.getDoctor().getPassword());
doctor.setStreetNo(apt.getDoctor().getStreetNo());
doctor.setTown(apt.getDoctor().getTown());
doctor.setUsername(apt.getDoctor().getUsername());
doctor.setSpecialization(apt.getDoctor().getSpecialization());
cpt.setPatient(patient);
cpt.setDoctor(doctor);
try{
sessionFactory = new Configuration().configure("hibernate1.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(patient);
session.save(doctor);
session.save(cpt);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
hibernate1.cfg.xml File:
<?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">
<session-factory>
<!-- Database connection settings -->
<!-- <property name="connection.driver_class">com.mysql.jdbc.Driver</property> -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<!-- <property name="connection.url">jdbc:mysql://174.143.132.195:3306/977266_EHR</property>
<property name="connection.username">977266_admin</property>
<property name="connection.password">EHr12345</property> -->
<property name="connection.url">jdbc:postgresql://localhost:5432/Centralized Database</property>
<property name="connection.username">postgres</property>
<property name="connection.password">project</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>
<property name="hibernate.default_catalog ">Centralized Database </property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<!-- Names the annotated entity class -->
<mapping class="com.ehr.admin.CentralPatient"/>
<mapping class="com.ehr.admin.CentralAppointment"/>
<mapping class="com.ehr.admin.CentralDoctor"/>
<mapping class="com.ehr.admin.CentralReceptionist"/>
</session-factory>
I shall b thankful to u :)
The error is caused by a space character in the table name Central Appointment. If you really want to use a table name with a space in it, you should quote it using backticks:
#Table(name = "`Central Appointment`")
But remember: you will also have to use similar quoting tricks when executing SQL queries directly in the database (in case of Postgres it's double quotes - select * from "Central Appointment" where ...). So it might be more convenient and also more colleague-friendly to not use such exotic table names and instead replace the space character with an underscore:
#Table(name = "Central_Appointment")
Just try following steps:-
In the hibernate.cfg.xml, add this property
hibernate.default_catalog = MyDatabaseName
In the hibernate.reveng.xml, add all the table filters like this
table-filter match-name="MyTableName" (just this, no catalog name here)
Regenerate hibernate code
Remove space if you have added while mentioning the column name
#Column(name="PassengerName")
I am getting the following exception -
org.hibernate.exception.SQLGrammarException: could not insert: [Employee]Here are the details:
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.connection.driver_class">sun.jdbc.odbc.JdbcOdbcDriver</property>
<property name="hibernate.connection.url">jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=D:/Hibernate.accdb</property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<property name="connection.pool_size">1</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">update</property>
<mapping resource="Employee.hbm.xml" />
</session-factory>
</hibernate-conf
Employee.hbm.xml
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
Employee.java
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
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;
}
}
ManageEmployee.java
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Add few employee records in database */
Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 10000);
}
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
}
Here is the full exception:
Output in console:
Hibernate: insert into EMPLOYEE (first_name, last_name, salary) values (?, ?, ?) select scope_identity()
org.hibernate.exception.SQLGrammarException: could not insert: [Employee]
Hibernate: insert into EMPLOYEE (first_name, last_name, salary) values (?, ?, ?) select scope_identity()
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2327)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2834)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at ManageEmployee.addEmployee(ManageEmployee.java:47)
at ManageEmployee.main(ManageEmployee.java:23)
Caused by: java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Missing semicolon (;) at end of SQL statement.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(Unknown Source)
at org.hibernate.id.IdentityGenerator$InsertSelectDelegate.executeAndExtract(IdentityGenerator.java:138)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
... 17 more
org.hibernate.exception.SQLGrammarException: could not insert: [Employee]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2327)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2834)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at ManageEmployee.addEmployee(ManageEmployee.java:47)
at ManageEmployee.main(ManageEmployee.java:24)
Caused by: java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Missing semicolon (;) at end of SQL statement.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(Unknown Source)
at org.hibernate.id.IdentityGenerator$InsertSelectDelegate.executeAndExtract(IdentityGenerator.java:138)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
... 17 more
org.hibernate.exception.SQLGrammarException: could not insert: [Employee]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2327)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2834)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at ManageEmployee.addEmployee(ManageEmployee.java:47)
at ManageEmployee.main(ManageEmployee.java:25)
Caused by: java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Missing semicolon (;) at end of SQL statement.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(Unknown Source)
at org.hibernate.id.IdentityGenerator$InsertSelectDelegate.executeAndExtract(IdentityGenerator.java:138)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
... 17 more
Hibernate: insert into EMPLOYEE (first_name, last_name, salary) values (?, ?, ?) select scope_identity()
Please help to resolve the exceptions.
Thanks in advance!
The MS Access dialect does not exists in the Hibernate library. This causes that Hibernate is not capable to detect the identity column and act as required for MS Access.
org.hibernate.exception.SQLGrammarException: could not insert: [Employee] Hibernate: insert into EMPLOYEE (first_name, last_name, salary) values (?, ?, ?) select scope_identity()
select scope_identity() is a TRANSACT-SQL instance not supported by MS Access.
You could do one of this options:
Don't use autogenerated id columns or no SQL standard fields.
Use a supported hibernate database insted of MS Access Hibernate doc.
Create your own hibernate dialect to support MS Access or use a thirdparty one to provide the special characteristics of MS Access.
Related to How can I use hibernate with MS Access?
I am creating a basic hibernate application for employee table in which I am adding, updating, deleting and displaying the record with the help of ManageEmployee class.
Actually, ManageEmployee is my test class and i am using Employee.java and Employee.hbm.xml file to do above things.
Details:
Database: Oracle 11 g
Hibernate version: hibernate-release-4.3.8.Final
Java Version: Java 1.8
Employee Table Details:
USER_ID NUMBER(15,0) No 1 1
FIRST_NAME VARCHAR2(20 BYTE) Yes 2
LAST_NAME VARCHAR2(20 BYTE) Yes 3
SALARY NUMBER(10,0) Yes 4
Error Log: you can see in the log that error is coming 3 times because I am adding Employee object 3 times in ManageEmployee.java class with addEmployee(...) method so I am assuming that problem is with the sequence generator for the column id.
Here I am using naive generator.
i.g.
Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
May 12, 2015 3:34:39 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-02289: sequence does not exist
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
at org.hibernate.id.SequenceGenerator.generateHolder(SequenceGenerator.java:122)
at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:115)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at ManageEmployee.addEmployee(ManageEmployee.java:47)
at ManageEmployee.main(ManageEmployee.java:23)
Caused by: java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1059)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:522)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:257)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:587)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:225)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:53)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:774)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:925)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1111)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4798)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:4845)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1501)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
... 13 more
May 12, 2015 3:34:39 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 2289, SQLState: 42000
May 12, 2015 3:34:39 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-02289: sequence does not exist
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
at org.hibernate.id.SequenceGenerator.generateHolder(SequenceGenerator.java:122)
at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:115)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at ManageEmployee.addEmployee(ManageEmployee.java:47)
at ManageEmployee.main(ManageEmployee.java:24)
Caused by: java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1059)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:522)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:257)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:587)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:225)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:53)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:774)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:925)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1111)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4798)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:4845)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1501)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
... 13 more
May 12, 2015 3:34:39 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 2289, SQLState: 42000
May 12, 2015 3:34:39 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-02289: sequence does not exist
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
at org.hibernate.id.SequenceGenerator.generateHolder(SequenceGenerator.java:122)
at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:115)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at ManageEmployee.addEmployee(ManageEmployee.java:47)
at ManageEmployee.main(ManageEmployee.java:25)
Caused by: java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1059)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:522)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:257)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:587)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:225)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:53)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:774)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:925)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1111)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4798)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:4845)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1501)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
... 13 more
First Name: a Last Name: b Salary: 2000
ManageEmployee.java file Code:
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Add few employee records in database */
Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 10000);
/* List down all the employees */
ME.listEmployees();
/* Update employee's records */
// ME.updateEmployee(empID1, 5000);
/* Delete an employee from the database */
// ME.deleteEmployee(empID2);
/* List down new list of the employees */
// ME.listEmployees();
}
/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
/* Method to READ all the employees */
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator =
employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to UPDATE salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to DELETE an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
Mapping File:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="user_id" type="int" column="user_id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
public class Employee {
private int user_id;
private String firstName;
private String lastName;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
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;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
}
Employee class is missing a sequence generator so hibernate cannot insert the row.
it should be something like this which increase the id count column by 1:
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQUENCE1")
#SequenceGenerator(name="SEQUENCE1", sequenceName="SEQUENCE1", allocationSize=1)
private int user_id;
after read up on Oracle sequences and how they function, as well as telling Hibernate that you are using a SEQUENCE (section 5.1.2.2.4) rather than a native generator, I have fixed my errors.
I have created a sequence in oracle database by the below query and updated my hbm.xml file
CREATE SEQUENCE TAB_CUSTOMER_SEQ
START WITH 1
MAXVALUE 999999999999999999999999999
MINVALUE 1
NOCYCLE
CACHE 20
NOORDER;
<id name="user_id" type="int" column="user_id">
<generator class="sequence">
<param name="sequence">TAB_CUSTOMER_SEQ</param>
</generator>
</id>
You didn't create a sequence for table EMPLOYEE to generate automatic USER_ID. This is your problem. So now you need to create a sequence for table EMPLOYEE in both DATABASE and your mapping file
try this:
<generator class="sequence"> <param name="sequence_name">SEQUENCE_NAME</param></generator>
The value for param was changed from just "sequence" to "sequence_name".
In my case I forget to add schema parameter in #SequenceGenerator(name = "TADDRESS_SEQ", sequenceName = "TADDRESS_SEQ", schema = "source", allocationSize = 1)