Following a tutorial found on yt channel i tried to make a simple application using Hibernate. When I execute the code I get a bunch of exceptions and I can't indentify the reason why. However, results of creating a table and inserting data is visible and it works fine - this confuses me the most. Below I provide code for necessary classes, persistence.xml and stack trace. How can I solve this problem?
STACK TRACE:
cze 24, 2017 7:39:31 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:375)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:359)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applyConstraintDropping(SchemaDropperImpl.java:331)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:230)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:154)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:126)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:112)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:144)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:309)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:889)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at org.hibernate.test.Main.main(Main.java:12)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernate_tests.employee' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2444)
at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:845)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:745)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
... 16 more
cze 24, 2017 7:39:31 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#363042d7] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
cze 24, 2017 7:39:31 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#59d2400d'
cze 24, 2017 7:39:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/hibernate_tests]
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="myDatabase" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="miki" />
<property name="javax.persistence.jdbc.password" value="***" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/hibernate_tests" />
<property name="hibernate.dialect.storage_engine" value="innodb" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
</persistence-unit>
Main.java
public class Main {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myDatabase");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Employee employee = new Employee();
Address address = new Address();
employee.setAddress(address);
employee.setFirstName("aaa");
employee.setLastName("bbb");
employee.setSalary(10000);
address.setLocalization("ccc");
address.setStreet("ddd");
address.setPostalCode("12-456");
/* entityManager.getTransaction().begin();
entityManager.persist(address);
entityManager.persist(employee);
entityManager.getTransaction().commit();*/
entityManager.close();
entityManagerFactory.close();
}
}
Employee.java
#Entity
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "Imie")
private String firstName;
#Column(name = "Nazwisko")
private String lastName;
#Transient
private double salary;
#OneToOne
#JoinColumn
private Address address;
/*sett.&gett*/
}
Address.java
#Entity
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "Miejscowosc")
private String localization;
#Column(name = "Ulica")
private String street;
#Column(name = "Kod_Pocztowy")
private String postalCode;
/*sett.&gett.*/
First make sure that your database hibernate_tests contain the table employee, Second to be sure put the name of your table in the Entity like :
#Entity
#Table(name = "employee", catalog = "hibernate_tests", schema = "schema_name")
public class Employee {...}
If you have a default schema then you don't need to use it just use :
#Entity
#Table(name = "employee")
public class Employee {...}
If this still not work you can check using the name of your database :
#Entity
#Table(name = "employee", catalog = "hibernate_tests")
public class Employee {...}
I managed to find what caused the problem. Everytime before execution of java code I manually dropped down tables. When program is executed, hibernate first tries to drop the tables assuming that they exist in the database. Since I dropped them previously there was exception that table doesn't exist.
When I don't drop tables manually there is no exception.
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.
I have following entities :
//Parent
#Entity
#Table(name = "PARENT")
public class Parent implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "PRIMARY_ID", updatable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer primaryID;
#OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER, targetEntity = Child.class)
private List<Child> child;
//Child
#Entity
#Table(name = "CHILD")
public class Child implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private ChildPK id;
#MapsId("primaryID") //Maps to primaryID in ChildPK
#ManyToOne
#JoinColumn(name = "PRIMARY_ID",nullable=false)
private Parent parent;
public Child() {
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="jpa-test" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="openjpa.ConnectionDriverName" value="com.ibm.db2.jcc.DB2Driver" />
<property name="openjpa.ConnectionURL"
value="jdbc:db2://host:port/dbname;" />
<property name="openjpa.ConnectionUserName" value="*****" />
<property name="openjpa.ConnectionPassword" value="*****" />
<property name="openjpa.jdbc.Schema" value="XXXXX" />
<property name="openjpa.jdbc.DBDictionary" value="db2" />
<property name="openjpa.jdbc.SchemaFactory" value="native(ForeignKeys=true)"/>
<property name="openjpa.jdbc.MappingDefaults"
value="jpa(ForeignKeyDeleteAction=restrict, JoinForeignKeyDeleteAction=restrict)" />
<property name="openjpa.Compatibility" value="StrictIdentityValues=true" />
<property name="openjpa.Log"
value="DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE" />
</properties>
</persistence-unit>
</persistence>
I am trying to delete a record from database by executing remove operation on parent. Please find below snippet for the same.
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jpa-test");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Parent parent = entityManager.find(Parent.class, 15149);
entityManager.getTransaction().begin();
entityManager.remove(parent);
entityManager.getTransaction().commit();
}
I am getting below exception.Please find below stack trace :
Exception in thread "main" <openjpa-2.2.3-SNAPSHOT-r422266:1715851 fatal store error> org.apache.openjpa.persistence.RollbackException: The transaction has been rolled back. See the nested exceptions for details on the errors that occurred.
FailedObject: com.entity.test.Parent-15149
at org.apache.openjpa.persistence.EntityManagerImpl.commit(EntityManagerImpl.java:594)
at com.test.Test.main(Test.java:76)
Caused by: <openjpa-2.2.3-SNAPSHOT-r422266:1715851 fatal general error> org.apache.openjpa.persistence.PersistenceException: The transaction has been rolled back. See the nested exceptions for details on the errors that occurred.
FailedObject: com.entity.test.Parent-15149
at org.apache.openjpa.kernel.BrokerImpl.newFlushException(BrokerImpl.java:2352)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2189)
at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:2087)
at org.apache.openjpa.kernel.BrokerImpl.beforeCompletion(BrokerImpl.java:2005)
at org.apache.openjpa.kernel.LocalManagedRuntime.commit(LocalManagedRuntime.java:81)
at org.apache.openjpa.kernel.BrokerImpl.commit(BrokerImpl.java:1529)
at org.apache.openjpa.kernel.DelegatingBroker.commit(DelegatingBroker.java:933)
at org.apache.openjpa.persistence.EntityManagerImpl.commit(EntityManagerImpl.java:570)
... 1 more
Caused by: <openjpa-2.2.3-SNAPSHOT-r422266:1715851 fatal general error> org.apache.openjpa.persistence.PersistenceException: THE RELATIONSHIP R_CNRLPH RESTRICTS THE DELETION OF ROW WITH RID X'000001271B' {prepstmnt 636888566 DELETE FROM XXXXX.PARENT WHERE PRIMARY_ID = ? [params=?]} [code=-532, state=23504]SQLCA OUTPUT[Errp=DSNXRSDL, Errd=-190, 13172769, 0, 13228485, -742129664, 0]
THE RELATIONSHIP R_CNRLPH RESTRICTS THE DELETION OF ROW WITH RID X'000001271B'
FailedObject: com.entity.test.Parent-15149
at org.apache.openjpa.jdbc.sql.DBDictionary.narrow(DBDictionary.java:4991)
at org.apache.openjpa.jdbc.sql.DBDictionary.newStoreException(DBDictionary.java:4957)
at org.apache.openjpa.jdbc.sql.DB2Dictionary.newStoreException(DB2Dictionary.java:571)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:136)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:78)
at org.apache.openjpa.jdbc.kernel.BatchingPreparedStatementManagerImpl.flushBatch(BatchingPreparedStatementManagerImpl.java:221)
at org.apache.openjpa.jdbc.kernel.BatchingConstraintUpdateManager.flush(BatchingConstraintUpdateManager.java:63)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:105)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:78)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.flush(JDBCStoreManager.java:732)
at org.apache.openjpa.kernel.DelegatingStoreManager.flush(DelegatingStoreManager.java:131)
... 8 more
Caused by: org.apache.openjpa.lib.jdbc.ReportingSQLException: THE RELATIONSHIP R_CNRLPH RESTRICTS THE DELETION OF ROW WITH RID X'000001271B' {prepstmnt 636888566 DELETE FROM XXXXX.PARENT WHERE PRIMARY_ID = ? [params=?]} [code=-532, state=23504]
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.wrap(LoggingConnectionDecorator.java:219)
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.wrap(LoggingConnectionDecorator.java:195)
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.access$1000(LoggingConnectionDecorator.java:59)
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator$LoggingConnection$LoggingPreparedStatement.executeUpdate(LoggingConnectionDecorator.java:1134)
at org.apache.openjpa.lib.jdbc.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:275)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager$CancelPreparedStatement.executeUpdate(JDBCStoreManager.java:1792)
at org.apache.openjpa.jdbc.kernel.PreparedStatementManagerImpl.executeUpdate(PreparedStatementManagerImpl.java:268)
at org.apache.openjpa.jdbc.kernel.BatchingPreparedStatementManagerImpl.flushSingleRow(BatchingPreparedStatementManagerImpl.java:250)
at org.apache.openjpa.jdbc.kernel.BatchingPreparedStatementManagerImpl.flushBatch(BatchingPreparedStatementManagerImpl.java:153)
... 13 more
The order of sql execution is wrong .Delete sql on parent is executed before child.
Currently i solved this by calling remove operation on child before parent. Is their any way through which i can delete child records by calling remove operation on parent.
I have a simple Entity written in Eclipse(Java), and I try to start my project with tome, but I get this exception.
Caused by: <openjpa-2.4.0-nonfinal-1598334-r422266:1599166 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: unexpected token: TO {stmnt 1004327302 ALTER TABLE Flight ADD COLUMN to VARCHAR(20)} [code=-5581, state=42581]
at org.apache.openjpa.jdbc.meta.MappingTool.record(MappingTool.java:559)
at org.apache.openjpa.jdbc.meta.MappingTool.record(MappingTool.java:455)
at org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory.synchronizeMappings(JDBCBrokerFactory.java:160)
at org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory.synchronizeMappings(JDBCBrokerFactory.java:164)
at org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory.newBrokerImpl(JDBCBrokerFactory.java:122)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:208)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:155)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:59)
at org.apache.openejb.assembler.classic.ReloadableEntityManagerFactory.createEntityManager(ReloadableEntityManagerFactory.java:160)
at org.apache.openejb.persistence.JtaEntityManagerRegistry.getEntityManager(JtaEntityManagerRegistry.java:119)
at org.apache.openejb.persistence.JtaEntityManager.getEntityManager(JtaEntityManager.java:96)
at org.apache.openejb.persistence.JtaEntityManager.proxyIfNoTx(JtaEntityManager.java:326)
at org.apache.openejb.persistence.JtaEntityManager.createQuery(JtaEntityManager.java:280)
at com.airline.utils.DatabaseUtils.deleteData(DatabaseUtils.java:42)
at com.airline.utils.DatabaseUtils.addTestDataToDB(DatabaseUtils.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:192)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:173)
at org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod(EjbObjectProxyHandler.java:308)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:303)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:92)
at org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:308)
... 44 more
Here is my Flight Entity with which I hava this problem :
#Entity
#NamedQueries({ #NamedQuery(name = "Flight.getAll", query = "SELECT f FROM Flight f") })
public class Flight implements Serializable {
#Transient
private static final long serialVersionUID = 1L;
public Flight() {
super();
}
public Flight(FlightDestination to, Integer flightPrice, Date date) {
super();
this.flightPrice = flightPrice;
this.date = date;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Enumerated(EnumType.STRING)
private FlightDestination to;
private Integer flightPrice;
#Temporal(TemporalType.DATE)
private Date date;}
The problem is with my FlightDestination to field
FlightDestination:
public enum FlightDestination {
SOFIA, MUNICH, BERLIN, PARIS, VALENCIA, ROME, NEW_YORK, BARCELONA}
And this is my persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="airline">
<description>Container Persistence Unit</description>
<jta-data-source>airlineDatabase</jta-data-source>
<class>com.airline.models.Passenger</class>
<class>com.airline.models.Flight</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<property name="openjpa.Log" value="DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE" />
<property name="openjpa.ConnectionFactoryProperties" value="PrintParameters=true" />
</properties>
Passenger is my other Entity which work perfectly when I remove Flight Entity.
to is a Keyword in mysql. Rename the property.
For more Information see https://dev.mysql.com/doc/refman/5.7/en/keywords.html
I tried connect to MSSQL from java with JPA and save entity. I create Entity:
a database connection successful
#Entity
#Table(name = "QCCC_USER")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "name", length = 32)
private String name;
#Column(name = "lastName", length = 32)
private String lastName;
#Column(name = "age")
private int age;
public User(String name, String lastName, int age) {
this.name = name;
this.lastName = lastName;
this.age = age;
}
public User() {
}
//other getters and setters
UserService :
public class UserService {
public EntityManager em = Persistence.createEntityManagerFactory("COLIBRI").createEntityManager();
public void add(User user){
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();
}
}
and in main methos i tried save user:
public class Main {
public static void main(String args[]) {
System.out.println("Hello world");
UserService userService = new UserService();
User user = new User("Pavel", "Petrashov", 25);
userService.add(user);
System.out.println("save");
}
}
But I have error before saving. It is this error:
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1316)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:881)
at Services.UserService.add(UserService.java:16)
at Main.main(Main.java:12)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: 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:364)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:205)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:185)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:169)
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.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:78)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:208)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:151)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:78)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:853)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:827)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:831)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:875)
... 7 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'QCCC_USER'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1635)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:426)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:372)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:6276)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1793)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:184)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:159)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:315)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)
My configuation:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="COLIBRI" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>Etityes.User</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="hibernate.connection.url" value="jdbc:sqlserver://*****:1433;DatabaseName=***"/>
<property name="hibernate.connection.username" value="***"/>
<property name="hibernate.connection.password" value="***"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
I tried mapping but not help. How do it?
Replace the following
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
with this
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
Or with this depending on your MSSQL Installation.
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServer2008Dialect"/>
Hope this helps.
You need to use DB specific Dialects.
You said you are using MSSQL DB but using MySQL dialect.
Change Dialect
org.hibernate.dialect.MySQLDialect to org.hibernate.dialect.SQLServerDialect.
It will work
I'm using Hibernate 3.6.0 with Mysql 5.5.15. I have an entity with a #GeneratedValue ID field. When I try to persist the entity it throws exception: No value specified for parameter 5. The fifth parameter is the ID field. How can I fix this problem?
The entity class:
#Entity
#Table(name = "T_DEVICE_HISTORY")
public class DeviceHistory {
#Id
#Column(name = "ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
#Column(name = "DEVICE_ID")
private String deviceId;
#Column(name = "GUID", length = 36)
private String guid;
#Column(name = "UPDATE_DATE")
private Date updated;
#Column(name = "STATUS", nullable = false)
#Enumerated(EnumType.STRING)
private DeviceStatus status;
// getters,setters ...
#PrePersist
public void setInitialState() {
setUpdated(new Date());
}
}
The code persisting the entity:
DeviceHistory deviceHistory = new DeviceHistory();
deviceHistory.setGuid(guid);
deviceHistory.setDeviceId(deviceId);
deviceHistory.setStatus(DeviceStatus.INACTIVE);
entityManager.persist(deviceHistory);
The stack trace:
06:12:58,123 ERROR [JDBCExceptionReporter] No value specified for parameter 5
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not insert: [com.evolok.idm.core.domain.DeviceHistory]
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:630)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:219)
at com.evolok.idm.core.domain.RestrictedUnregisterPerDurationDeviceManagementPolicyDelegate.unregisterDevice(RestrictedUnregisterPerDurationDeviceManagementPolicyDelegate.java:78)
at com.evolok.idm.core.domain.DeviceManagementPolicyEntity.unregisterDevice(DeviceManagementPolicyEntity.java:86)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:157)
at com.evolok.idm.core.domain.DeviceManagementPolicyEntity$$EnhancerByCGLIB$$2ff84b00.unregisterDevice(<generated>)
at com.evolok.idm.services.core.UserProfileComponent.unregisterDevice(UserProfileComponent.java:479)
at com.evolok.idm.notification.proxies.UserProfileServiceNotificationProxy.unregisterDevice(UserProfileServiceNotificationProxy.java:186)
at com.evolok.idm.services.web.endpoints.rest.UserProfileResource.unregisterDevice(UserProfileResource.java:567)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.sca4j.pojo.component.InvokerInterceptor.invoke(InvokerInterceptor.java:192)
at org.sca4j.pojo.component.InvokerInterceptor.invoke(InvokerInterceptor.java:165)
at org.sca4j.fabric.component.scope.RequestScopeInterceptor.invoke(RequestScopeInterceptor.java:40)
at org.sca4j.rs.runtime.RsSourceWireAttacher$RsMethodInterceptor.intercept(RsSourceWireAttacher.java:163)
at com.evolok.idm.services.web.endpoints.rest.UserProfileResource$$EnhancerByCGLIB$$99ca8d93.unregisterDevice(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:156)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:67)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:163)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:111)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:71)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:111)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:63)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:654)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:612)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:603)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:309)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:425)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:590)
at org.sca4j.rs.runtime.rs.RsWebApplication.service(RsWebApplication.java:148)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.sca4j.runtime.webapp.ServletHostImpl.service(ServletHostImpl.java:138)
at org.sca4j.runtime.webapp.SCA4JServlet.service(SCA4JServlet.java:85)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:534)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1351)
at com.evolok.idm.web.TransactionFilter.doFilter(TransactionFilter.java:47)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1322)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:473)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:516)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:929)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:403)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:184)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:864)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:247)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:151)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:114)
at org.eclipse.jetty.server.Server.handle(Server.java:352)
at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:596)
at org.eclipse.jetty.server.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:1051)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:590)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:212)
at org.eclipse.jetty.server.HttpConnection.handle(HttpConnection.java:426)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:508)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.access$000(SelectChannelEndPoint.java:34)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:40)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:451)
at java.lang.Thread.run(Thread.java:695)
Caused by: org.hibernate.exception.SQLGrammarException: could not insert: [com.evolok.idm.core.domain.DeviceHistory]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
at org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:49)
at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:131)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:87)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:213)
... 68 more
Caused by: java.sql.SQLException: No value specified for parameter 5
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2176)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1993)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1937)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1922)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)
... 83 more
The generated statement:
insert into T_DEVICE_HISTORY (DEVICE_ID, GUID, STATUS, UPDATE_DATE, ID) values (?, ?, ?, ?, ?)
EDIT: Table structure:
CREATE TABLE `T_DEVICE_HISTORY` (
`ID` bigint(20) NOT NULL AUTO_INCREMENT,
`DEVICE_ID` varchar(255) DEFAULT NULL,
`GUID` varchar(36) DEFAULT NULL,
`STATUS` varchar(255) NOT NULL,
`UPDATE_DATE` datetime DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Edit 2 - persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="evolok-idm" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.evolok.idm.core.domain.DeviceHistory</class>
<!-- other classes... -->
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/evolok-idm-web"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.autocommit" value="false"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.connection.isolation" value="4"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="false"/>
</properties>
</persistence-unit>
</persistence>
From your code I can see that the updateDate is missing... is tat nullable field ?
AUTO is default strategy so you can remove. and try the following equivalent definition..
#Id
#Column(name = "ID")
#GeneratedValue
private long id;
Change your entity as follows, you need to add default constructor.
#Entity
#Table(name = "T_DEVICE_HISTORY")
public class DeviceHistory implements java.io.Serializable {
public DeviceHistory(){
super();
id = null ;
}
#Id
#Column(name = "ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;