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
Related
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 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.
I'm trying to make a simple example of persistence using JPA with Hibernate as provider. I'm using MySQL as database. But I'm getting this error:
Hibernate: insert into person (NAME, DTYPE) values (?, 'person')
dez 21, 2014 8:35:01 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1054, SQLState: 42S22
dez 21, 2014 8:35:01 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Unknown column 'DTYPE' in 'field list'
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1187)
at Test.main(Test.java:17)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
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:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
... 1 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'DTYPE' in 'field list'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.Util.getInstance(Util.java:383)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1062)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4208)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4140)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2597)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2758)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2826)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2334)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2262)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2246)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 22 more
Here my codes
1) Test.java
public class Test {
public static void main(String[] args){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ExampleJPA");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
for(int i = 1; i < 11; i++)
{
Person p = new Person();
p.setName("pessoa " + i);
em.persist(p);
}
em.getTransaction().commit();
em.close();
}
}
2) Person.java
public class Person {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3) persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="ExampleJPA" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<mapping-file>META-INF/person.xml</mapping-file>
<class>Person</class>
<properties>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/gerenciador"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
4) Person.xml
<?xml version="1.0" encoding="UTF-8" ?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
version="1.0">
<entity class="Person" name="person">
<table name="person"/>
<attributes>
<id name="id">
<generated-value strategy="AUTO"/>
</id>
<basic name="name">
<column name="NAME" length="255"/>
</basic>
</attributes>
</entity>
</entity-mappings>
Do you have inheritance in your hibernate model? The name of the discriminator column in hibernate defaults to "DTYPE" hence the confusion. Go through your project model again and reply back.
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