OpenJPA : Cascade Delete issue - java

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.

Related

org.hibernate.hql.internal.ast.QuerySyntaxException: transaction is not mapped

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.

Hibernate : All tables in SQL Server database are not auto-created

create tables from Java in database on Microsoft SQL Server 2012. All tables are created, except one table. I'm using JPA and there 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="teknikPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/teknikNDataSource</jta-data-source>
<class>com.royken.entities.Bloc</class>
<class>com.royken.entities.Elements</class>
<class>com.royken.entities.Organes</class>
<class>com.royken.entities.SousOrganes</class>
<class>com.royken.entities.Utilisateurs</class>
<class>com.royken.entities.Zone</class>
<class>com.royken.entities.Reponse</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
<property name="eclipselink.logging.level" value="OFF"/>
<property name="eclipselink.cache.shared.default" value="false"/>
<property name="eclipselink.query-results-cache" value="false"/>
<!-- <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.engine.transaction.jta.platform.internal.SunOneJtaPlatform" />
<property name="hibernate.transaction.factory_class" value="org.hibernate.engine.transaction.internal.jta.JtaTransactionFactory"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.classloading.use_current_tccl_as_parent" value="false"/>-->
<!--<property name="javax.persistence.schema-generation.database.action" value="create"/> -->
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
This is how I define my classes :
#Entity
#XmlRootElement(name = "elements")
#Table(name = "ELEMENTS")
#XmlAccessorType(XmlAccessType.FIELD)
public class Elements implements Serializable {
private static final long serialVersionUID = 1L;
#OneToMany(mappedBy = "elements")
private List<Reponse> reponses;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
private Long id;
#Version
#Column(name = "VERSION")
private int version;
#Column(name = "NOM")
private String nom;
#Column(columnDefinition = "tinyint(1) default true", name = "HASBORNS")
private boolean hasBorns;
#Column(columnDefinition = "tinyint(1) default true", name = "CRITERIAALPHA")
private boolean criteriaAlpha;
}
I have defined 7 tables like that, but only 6 tables are created, Elements tables is not created. When I change the datasource by using a mysql database (without changing any part of code), all my tables are well created.
What can be the issue ?
The image bellow shows the result in SQL server, Elements table is not present.
In your persistence.xml Use :
<property name="eclipselink.deploy-on-startup" value="true" />
In your code, you may use:
import javax.ejb.Stateless;
import entity.userEntity;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
Look for EntityManager
#PersistenceContext
private EntityManager entityManager;
and then use it like :
Query query = entityManager.createQuery("SELECT e FROM Elements e WHERE e.id= :idValue");
query.setParameter("idValue", 1);
Elements elements = null;
try {
elements = (Elements) query.getSingleResult();
} catch (NoResultException ex) {
ex.printStackTrace();
}
You may refer to this
If that too doesn't help look here
I found the solution to my problem. Entity table was not created because SQL Server does not accept true as default value for hasborns and criteriaalpha. Also, it does not now the size to allocate to tinyint type. So it throws an error during table creation. To solve this issue, I replaced:
#Column(columnDefinition = "tinyint(1) default true", name = "HASBORNS")
private boolean hasBorns;
#Column(columnDefinition = "tinyint(1) default true", name = "CRITERIAALPHA")
private boolean criteriaAlpha;
with:
#Column(columnDefinition = "BIT default 1", name = "HASBORNS", length = 1)
private boolean hasBorns ;
#Column(columnDefinition = "BIT default 1", name = "CRITERIAALPHA", length = 1)
private boolean criteriaAlpha ;
And it worked

Tomcat(TomEE) error while creating JPA

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

JPA ManyToMany anotation for not load all items in set

I have User class and BattleReportILogItem class. This class (User, BattleReportILogItem) are #Entity.
User have 0..N BattleReportILogItem.
USER
#Entity
#Table(name = DomainConstant.TABLE_USER)
public class User implements Serializable {
#Id
#Column(name = DomainConstant.DOMAIN_USER_ID)
#GeneratedValue
private Long userId;
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(name = DomainConstant.VIEW_USER_BATTLE_LOGS, joinColumns = {
#JoinColumn(name = DomainConstant.DOMAIN_USER_ID)}, inverseJoinColumns = {
#JoinColumn(name = DomainConstant.DOMAIN_BATTLE_REPORT_ID)})
private Set<BattleReportILogItem> setOfBattleLogs = new HashSet<>();
....(other stuff, get and set methods...)
BattleReportILogItem
#Entity
#Table(name = DomainConstant.TABLE_BATTLE_REPORT)
public class BattleReportILogItem implements Serializable {
#Id
#GeneratedValue
#Column(name = DomainConstant.DOMAIN_BATTLE_REPORT_ID)
private Long BattleReportILogItemId;
#ManyToMany(mappedBy = "setOfBattleLogs")
private Set<User> setOfBattleLogs = new HashSet<>();
....(other stuff, get and set methods...)
The problem is, that I load User program loads all data in private Set<BattleReportILogItem> setOfBattleLogs = new HashSet<>();. This mean 1 000 000 000 items in my set setOfBattleLogs. I don't want load data to this set. For load data i have BattleReportLogItemDao DAO.
Is there any solution how to NOT LOAD DATA to my set?
I hope, you understand me... :-))
Thank you for your help.
EDIT persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="com.donutek" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/db"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.validator.apply_to_ddl" value="true" />
<property name="connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider"/>
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="300"/>
</properties>
</persistence-unit>
</persistence>
EDIT 2:
For load user I am using the code:
#Override
public User findByEmail(String email) {
TypedQuery<User> q = em.createQuery("SELECT u FROM " + User.class.getSimpleName() + " u WHERE u.email = :uemail", User.class);
q.setParameter("uemail", email);
try {
return q.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
You can use the parameter fetchtype Lazy. Now your strategy seems to be Eager.

Getting "java.sql.SQLException: No value specified for parameter" for a #GeneratedValue field

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;

Categories