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
Related
I have an error like this : java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Transaction is not mapped [SELECT NEW model.DailyReport(SUM(c.amount), date(c.transactionTimestamp)) FROM transaction AS c GROUP BY date(c.transactionTimestamp)]
and here is my code :
String queryStr = "SELECT NEW model.DailyReport(SUM(c.amount), date(c.transactionTimestamp)) FROM Transaction AS c GROUP BY date(c.transactionTimestamp)";
TypedQuery<Transaction> query = entityManager.createQuery(queryStr, Transaction.class);
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.getResultList();
Help me, BTW I'm new in JPA. Thx!
Edited :
Here is my Transaction Class :
#Table(name = "Transaction")
#Entity
public class Transaction implements Serializable{
#Id // ID
#Column(length = 32, nullable = false)
private String id;
#Column(length = 32, nullable = false)
private String srcAccountId;
#Column(length = 32, nullable = false)
private String dstAccountId;
private Double amount;
#JsonFormat(pattern = Json.JSON_FORMAT_TIMESTAMP)
#Temporal(TemporalType.TIMESTAMP)
private Date transactionTimestamp;
// Setter and Getter here
}
And here is my persistence.xml :
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="RestNeo-1" transaction-type="JTA">
<jta-data-source>java:jboss/datasources/RestNeoDS</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="false"/>
</properties>
</persistence-unit>
</persistence>
Thank you.
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 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;
My entity class :
public class ACCOUNT implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name = "USERNAME")
private String Username;
#Column(name = "PASSWORD")
private String Password;
public ACCOUNT(String user,String pass)
{
this.Username=user;
this.Password=pass;
}
// geter and setter
my persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="transactions-optional">
<provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
<class>com.materialshop.server.Datastore.ACCOUNT</class>
<exclude-unlisted-classes/>
<properties>
<property name="datanucleus.NontransactionalRead" value="true"/>
<property name="datanucleus.NontransactionalWrite" value="true"/>
<property name="datanucleus.nontx.atomic" value="true"/>
<property name="datanucleus.ConnectionURL" value="appengine"/>
</properties>
</persistence-unit>
</persistence>
Now persist account and it was successful
ACCOUNT ac=new ACCOUNT("admin","123");
em.persist(ac);
I checked
http://localhost:8888/_ah/admin
and yes ,there is ACOUNT entity with 1 record admin and 123
but when I use JPQL to get all entity , it returned null
Query q=new Query("SELECT ac FROM ACCOUNT ac");
List<ACCOUNT> list=q.getResultList();
even with
em.find(ACCOUNT.class,"admin");
return null too
Did i miss something ? Please help me , very grateful for your help