When I am trying to save a ManyToMany relation I get a database exception:
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "INVERSES_ID"; SQL statement:
INSERT INTO m2m_owner_inverse (inverses_ID, owners_ID) VALUES (?, ?) [23502-184]
Error Code: 23502
Call: INSERT INTO m2m_owner_inverse (inverses_ID, owners_ID) VALUES (?, ?)
bind => [null, 1]
It is strange since I see in the log that both of the instances are inserted:
[EL Fine]: sql: 2016-02-22 13:18:32.67--ClientSession(1546269015)--Connection(1894667608)--INSERT INTO M2MOWNER (NAME) VALUES (?)
bind => [null]
[EL Fine]: sql: 2016-02-22 13:18:32.676--ClientSession(1546269015)--Connection(1894667608)--CALL IDENTITY()
[EL Fine]: sql: 2016-02-22 13:18:32.716--ClientSession(1546269015)--Connection(1894667608)--INSERT INTO M2MINVERSE (NAME) VALUES (?)
bind => [null]
[EL Fine]: sql: 2016-02-22 13:18:32.718--ClientSession(1546269015)--Connection(1894667608)--CALL IDENTITY()
The ChangeTracking is an eclipselink feature and the application needs a javaagent to run:
java -javaagent:eclipselink.jar
Without ChangeTracking and the agent it works as expected, the insertion happens.
It also works if I save the owner side (see the commented line)
The files can be found on github: https://github.com/zbiro/many2many
The sample can be started with
gradle start
The java files:
public class M2MTest {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("m2m-pu");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
M2MOwner owner = em.merge(new M2MOwner());
em.flush();
M2MInverse inverse = new M2MInverse();
owner.getInverses().add(inverse);
inverse.getOwners().add(owner);
inverse = em.merge(inverse); // does not work if agent is used
//owner = em.merge(owner); // works in all cases
em.flush();
em.getTransaction().commit();
em.close();
emf.close();
}
}
#Entity
#ChangeTracking(ChangeTrackingType.ATTRIBUTE)
public class M2MOwner {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
#ManyToMany(cascade={CascadeType.ALL})
#JoinTable(name="m2m_owner_inverse")
private Set<M2MInverse> inverses = new HashSet<>();
public Set<M2MInverse> getInverses() {
return inverses;
}
}
#Entity
#ChangeTracking(ChangeTrackingType.ATTRIBUTE)
public class M2MInverse {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
#javax.persistence.ManyToMany( cascade = { CascadeType.ALL }, mappedBy="inverses")
private Set<M2MOwner> owners = new HashSet<>();
public Set<M2MOwner> getOwners() {
return owners;
}
}
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="m2m-pu" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>M2MOwner</class>
<class>M2MInverse</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:tests;LOCK_TIMEOUT=10000" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<property name="eclipselink.logging.parameters" value="true" />
<property name="eclipselink.logging.level.sql" value="FINEST" />
</properties>
</persistence-unit>
</persistence>
build.gradle
apply plugin: "java"
repositories {
mavenCentral()
}
configurations {
eclipseLink { transitive = false }
}
ext.libs = [:]
libs.eclipseLink = 'org.eclipse.persistence:eclipselink:2.6.2'
dependencies {
compile 'com.h2database:h2:1.4.191'
compile libs.eclipseLink
eclipseLink libs.eclipseLink
}
task start(type: JavaExec) {
dependsOn build
classpath = sourceSets.main.runtimeClasspath
main = 'M2MTest'
jvmArgs = ["-javaagent:${configurations.eclipseLink.singleFile}"]
}
My question is why it is happening and how I could avoid it.
Related
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
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.
Hello I have a rather simple relationship.
A Patient can have several Measurements. I used a H2 file database and Hibernate.
The Problem:
When I try to remove a Measurement from a Patient I get a the following Error.
Referential integrity constraint violation: "FK_O423U89KR6K78NNG1PO0ISDF6: PUBLIC.PATIENTVO_MEASUREMENTVO FOREIGN KEY(MEASUREMENTS_ID) REFERENCES PUBLIC.MEASUREMENTVO(ID) (X'3c2b9ee868f645c5a5a743c2a409ab5e')"; SQL statement:
delete from MeasurementVO where id=? [23503-185]
The Patient part of the Relationship:
#OneToMany(orphanRemoval=true, cascade={CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE}, mappedBy = "patient", fetch = FetchType.EAGER)
public List<MeasurementVO> getMeasurements() {
return measurements;
}
The Measurement Part of the Relationship:
#ManyToOne
#JoinColumn
public PatientVO getPatient() {
return patient.get();
}
The function which should delete a Measurement:
#Override
#Transactional
public boolean removeMeasurementFromPatient(PatientVO patientVO, MeasurementVO measurementVO) {
EntityManager manager = emProvider.get();
PatientVO patientAlreadyInDB = manager.find(PatientVO.class, patientVO.getPatientId());
if (patientAlreadyInDB != null) {
patientAlreadyInDB.getMeasurements().removeIf(measurement -> measurement.getId().equals(measurementVO.getId()));
manager.merge(patientAlreadyInDB);
return true;
} else {
return false;
}
}
And the 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="db" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>ch.fhnw.ima.doggait.vo.PatientVO</class>
<class>ch.fhnw.ima.doggait.vo.MeasurementVO</class>
<class>ch.fhnw.ima.doggait.vo.MeasurementAttributesVO</class>
<class>ch.fhnw.ima.doggait.vo.TimeMark</class>
<properties>
<property name="connection.driver_class" value="org.h2.Driver"/>
<!-- <property name="hibernate.connection.url" value="jdbc:h2:mem:db"/>-->
<property name="hibernate.connection.url" value="jdbc:h2:file:./database/dogdatabase"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<!--<property name="hibernate.hbm2ddl.auto" value="create-drop"/>-->
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
Does somebody has a hint why I am not able to remove a Measurement from a patient and then persist him/her?
From the name of the table whose constraint is being violated (PATIENTVO_MEASUREMENTVO), seems like you have an intermediate table to implement the relation. This is normally used in many to many relationships.
Being a one to many relationship why not just adding a foreign key from the Measurement to Patient?
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
Seems like a simple enough thing. I've used Hibernate sequences to MySQL and Oracle in the past but now using JPA2/Hibernate4 to Postgresql 9.1 and keep getting exceptions. Any ideas? I've tried different flavors of GenerationType.SEQUENCE and GenerationType.AUTO but nothing works. I definitely need help.
[1] Postgresql 9.1 DDL
-- removed CACHE 100
create sequence my_seq INCREMENT 1 MINVALUE 1 MAXVALUE 2147483647 START 1;
create table my_table (
id integer NOT NULL DEFAULT nextval('my_seq'),
ident text NOT NULL CONSTRAINT ident_uniq UNIQUE,
cname text NOT NULL,
created timestamp WITH TIME ZONE NOT NULL DEFAULT ('now'::text)::timestamp(6) with time zone,
lastmodified timestamp WITH TIME ZONE NOT NULL DEFAULT ('now'::text)::timestamp(6) with time zone,
CONSTRAINT my_table_pkey PRIMARY KEY(id)
);
insert into my_table (ident, cname) values ('test001', 'Test 001');
[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_2_0.xsd"
version="2.0" >
<persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<description>Persistence unit</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/mydb" />
<property name="javax.persistence.jdbc.user" value="user" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="hibernate.hbm2ddl.auto" value="validate"/>
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="false" />
<property name="prefer_sequence_per_entity" value="true" />
</properties>
</persistence-unit>
</persistence>
[3] Entity code
package com.mypackage;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Transient;
#Entity(name="my_table")
public class MyTable {
#SequenceGenerator(name="foo", sequenceName="my_seq", allocationSize=1, initialValue=1)
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "foo")
#Id
#Column(name = "id")
private long id;
private String ident;
private Timestamp created;
private Timestamp lastmodified;
}
[5] JUnit
public class Test_MyTable {
#Test
public void test_1() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPersistenceUnit");
EntityManager em = emf.createEntityManager();
List<MyTable> list = em.createQuery("from my_table", MyTable.class).getResultList();
int size = ( (list == null) || (list.size() <= 0) ) ? 0 : list.size();
if (size == 0) {
System.out.println("Didn't find any MY_TABLE records");
} else {
System.out.println("Found [" + size + "] MY_TABLE records");
}
em.close();
emf.close();
}
}
[3] Exception
javax.persistence.PersistenceException: [PersistenceUnit: MyPersistenceUnit] Unable to build EntityManagerFactory
Caused by: org.hibernate.HibernateException: Wrong column type in public.my_table for column id. Found: serial, expected: int8
Change
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "foo")
to
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "foo")
else it won't use a sequence strategy, but an identity strategy.
And try to remove the default value of the PK column, and to define the column as bigint, since int is only 4 bytes and Java longs have 8 bytes.