I have two different java web application than access a shared postgres database for reading and writing. My first web application in deployed on apache tomcat and my second web application is deployed on jboss. When one of my two application write a new row on a table of database, the sequence is incremented of 1 and its value is assigned to primary key and row is stored correctly. When the other application try to write a new row on the same table, the id than was assigned is not synchronized with sequence, and I have exception for duplicate primary key. In my java class I use this annotation for define my id:
@Id
@SequenceGenerator(name = "my_seq", sequenceName = "my_seq_on_db", allocationSize=1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_seq")
Long my_id;
this 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="MyPersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/myDatasouce</jta-data-source>
<class>myPackage.myClass</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
persistence.xml
and tell us which JPA provider you're using. Ideally, log the SQLINSERT
statements and post them; I suspect your provider isn't using the database's native capability to assign a value, and you're hitting a race condition.persistence.xml
isn't an answer. You can edit this post instead.