Multiple access to the same shared database postgres sequence - java

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>

Related

MySQL geospatial data (POINT) and JPA in Netbeans

I need to just fetch some geospatial data (simple coordinates - POINTS) from MySQL db and use them in Java (NetBeans project). This is what I did so far:
Created MySQL db with following table:
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lokacija` point DEFAULT NULL,
`info` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
I also created NetBeans project and set up JPA and everything, added hibernate-spatial library to it and here is my persistence.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="testGisPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>model.Test</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.spatial.dialect.mysql.MySQLSpatialDialect"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:8889/dipl?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="root"/>
</properties>
</persistence-unit>
</persistence>
After that, created entity and besides all other properties, it also contains following:
...
#Column(name = "lokacija")
#Type(type="org.hibernate.spatial.GeometryType")
private Point lokacija;
#Column(name = "info")
private String info;
...
I also generated REST facade directly from NetBeans and I tried to print all items I fetch from the db (currently I have only two items with descriptions "first" and "second" and locations (1,1)) and here is what I get:
LOCATION: null
INFO: first
LOCATION: null
INFO: second
Any suggestions what else I should do in order to make this work?

Arquillian Entities with schema

I am setting up Arquillian with OpenEJB. I want to test a webservice with access to a database. I was able to setup everything with my own bean and entity for testing purposes.
Now I am adding all classes and dependencies and trying to start the test. But it fails to deploy, because my entities have an schema defined in its #Table annotation.
arquillian.xml
<arquillian xmlns="http://jboss.org/schema/arquillian"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://jboss.org/schema/arquillian
http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<engine>
<property name="deploymentExportPath">target/deployments</property>
</engine>
<container default="true" qualifier="openejb-embedded-4">
<configuration>
<property name="properties">
testDatabase = new://Resource?type=DataSource
</property>
</configuration>
</container>
</arquillian>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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">
<persistence-unit name="newejb" transaction-type="JTA">
<jta-data-source>testDatabase</jta-data-source>
<class>[...].AuftragsHistorie</class>
<properties>
<property name="openejb.jpa.init-entitymanager" value="true" />
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
</properties>
</persistence-unit>
</persistence>
AuftragsHistorie.java
#Entity(name = "AuftragsHistorie")
#SequenceGenerator(
name = "AUFTRAGSHISTORY_GENERATOR",
sequenceName = "SEQ_T_PUB_INET_DAF",
allocationSize = 1
)
#Table(
name = "T_PUB_INET_DAF",
schema = "DATA_SCHEMA"
)
public class AuftragsHistorie implements Serializable {
last part of stacktrace
Caused by: org.apache.openjpa.lib.jdbc.ReportingSQLException: invalid schema name: DATA_SCHEMA in statement [CREATE TABLE DATA_SCHEMA.T_PUB_INET_DAF (ID BIGINT NOT NULL, AUFTRAGS_ART_NAME VARCHAR(255) NOT NULL, ERF_DATUM TIMESTAMP NOT NULL, VERS_NR VARCHAR(255) NOT NULL, PRIMARY KEY (ID))] {stmnt 2112059634 CREATE TABLE DATA_SCHEMA.T_PUB_INET_DAF (ID BIGINT NOT NULL, AUFTRAGS_ART_NAME VARCHAR(255) NOT NULL, ERF_DATUM TIMESTAMP NOT NULL, VERS_NR VARCHAR(255) NOT NULL, PRIMARY KEY (ID))} [code=-4850, state=3F000]
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.wrap(LoggingConnectionDecorator.java:218)
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.wrap(LoggingConnectionDecorator.java:202)
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.access$700(LoggingConnectionDecorator.java:58)
at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator$LoggingConnection$LoggingStatement.executeUpdate(LoggingConnectionDecorator.java:913)
at org.apache.openjpa.lib.jdbc.DelegatingStatement.executeUpdate(DelegatingStatement.java:118)
at org.apache.openjpa.jdbc.schema.SchemaTool.executeSQL(SchemaTool.java:1231)
at org.apache.openjpa.jdbc.schema.SchemaTool.createTable(SchemaTool.java:976)
at org.apache.openjpa.jdbc.schema.SchemaTool.add(SchemaTool.java:552)
at org.apache.openjpa.jdbc.schema.SchemaTool.add(SchemaTool.java:364)
at org.apache.openjpa.jdbc.schema.SchemaTool.run(SchemaTool.java:341)
at org.apache.openjpa.jdbc.meta.MappingTool.record(MappingTool.java:505)
... 109 more
I already tried adding the schema via #CreateShema annotation and adding a lot of different properties, but nothing solved the problem.
Arquillian starts a HSQL Database.
I ended up using an Arquillian extension like this:
https://github.com/arquillian/arquillian-examples/tree/master/arquillian-lifecycle-extension-tutorial
I start a H2 database before the deployment, create the required schemata and shut it down after undeployment.

Java EE - IntelliJ - javax.persistence.Table - table name cannot be resolved

I am trying to resolve this problem since 3 days, I cannot solve it. I read about, that IntelliJ is mixing up something. I found that thread and similar answers in other threads, and tried to to exactly the same, but it did not work: Cannot resolve column 'USERNAME' less
My Persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="NewPersistenceUnit">
<jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
<class>Book</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"></property>
<property name="hibernate.show_sql" value="true"></property>
</properties>
</persistence-unit>
</persistence>
My class Book where I want to set the name. The Table "Book" cannot be resolved.
#Entity
#Table(name = "BOOK")
public class Book implements Serializable{
#Id
private int id;
}
In addition to what the answer you posted, in the persistence tool window
(view -> tool windows -> persistence), you should see persistence.xml, right click and select "assign data source" and assign your configured datasource.
More info here: My Favorited Question

PostgreSQL and Hibernate JPA not working

I'm trying to use JPA in Wildfly (which uses Hibernate) with PostgreSQL. I turned on hibernate.show_sql so I can execute the same query in PgAdmin III.
The query is this one (EDIT: issuemanager_sch is the schema. Without it even in PgAdmin the query fails with "relation does not exist" error):
select issuetypet0_.id_issue_type as id_issue1_3_, issuetypet0_.name as name2_3_ from issuemanager_sch.issue_type issuetypet0_
When executed by Hibernate this is showed in both PostgreSQL log and Wildfly log :
relation "issuemanager_sch.issue_type" does not exist character 87
However, when I copy (to grant I'm executing the exact same query), paste and run the query in PgAdmin III it's executed normally and I get the results.
What could possibly be wrong with my configurations? (I tried with both quoted and unquoted queries and the results are the same: fails for Hibernate, works in PgAdmin III)
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">
<persistence-unit name="PersistenceManager" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<non-jta-data-source>java:/datasources/issuemanager_pg</non-jta-data-source>
<class>com.im.issuerepository.domain.IssueTO</class>
<class>com.im.issuerepository.domain.IssueTypeTO</class>
<class>com.im.userrepository.domain.UserTO</class>
<class>com.im.userrepository.domain.GroupTO</class>
<class>com.im.userrepository.domain.RoleTO</class>
<validation-mode>NONE</validation-mode>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL9Dialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.default_schema" value="issuemanager_sch"/>
</properties>
</persistence-unit>
</persistence>
EDIT: issue_type table:
CREATE TABLE issuemanager_sch.issue_type
(
id_issue_type bigint NOT NULL DEFAULT nextval('issuemanager_sch.issue_type_seq'::regclass),
name text NOT NULL,
CONSTRAINT "PK_ISSUE_TYPE" PRIMARY KEY (id_issue_type)
)
EDIT: IssueTypeTO mapping:
#Entity
#Table(name = "issue_type")
public class IssueTypeTO implements Serializable{
#Id
#Column(name = "id_issue_type")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "issue_type_seq")
#SequenceGenerator(name = "issue_type_seq", sequenceName = "issue_type_seq", allocationSize = 1)
private Long idIssueType;
#Column(name = "name", length = 45)
private String name;
// getters and setters
}

Multiple persistance unit in persistence.xml creating tables in one another

I am using JPA (hibernate) and have the following persistence.xml
<persistence version="1.0" 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">
<persistence-unit name="DB1" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.dto1.AccessRight</class>
<class>com.dto1.Component</class>
<class>com.dto1.UserRight</class>
<properties>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
<persistence-unit name="DB2" transaction-type="RESOURCE_LOCAL">
<class>com.dto2.Auditlog</class>
<properties>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
In code i use the following to get EntityManager factory the following way:
private static final EntityManagerFactory emf_db1 = Persistence.createEntityManagerFactory(DB1_PU_NAME, getConnectionProps(DB1_PU_NAME));
private static final EntityManagerFactory emf_db2 = Persistence.createEntityManagerFactory(DB2_PU_NAME, getConnectionProps(DB2_PU_NAME));
private static Map<String, String> getConnectionProps(String pu) {
Map<String, String> dbConfProps = null;
dbConfProps = new HashMap<String, String>();
// Configure the Database properties
ConnectionEntity conn_en = ConnectionEntity.getConnectionEntity();
dbConfProps.put("hibernate.dialect", conn_en.getDbdialect());
if (pu.equals(DB2_PU_NAME)) {
dbConfProps.put("hibernate.connection.url", conn_en.getDB2_dburl());
} else {
dbConfProps.put("hibernate.connection.url", conn_en.getDB1_dburl());
}
dbConfProps.put("hibernate.connection.driver_class", conn_en.getDriver());
dbConfProps.put("hibernate.connection.username", conn_en.getUsername());
dbConfProps.put("hibernate.connection.password", conn_en.getPassword());
return dbConfProps;
}
public static javax.persistence.EntityManager getInstance(String persistanceUnit) {
logger.log("getInstance entered");
if (persistanceUnit.equalsIgnoreCase(DB1_PU_NAME)) {
return emf_idm.createEntityManager();
}
return emf_logs.createEntityManager();
}
Where conn_en has the dbConfiguration in a property file and reads from it. The thing what happens is that both database create each other tables on runtime whenever my application performs some task. During the execution i have to make entries in the tables of both databases. DB1 creates extra tables from DB2 and vice-versa. Any suggestion what is going wrong here?
Use <exclude-unlisted-classes>true</exclude-unlisted-classes> in both of your persistence units. As per this document entities that are not listed in particular persistence unit will not be managed by this unit!
Update: As per new specification for JPA 2 in jsr317
The set of managed persistence classes that are managed by a persistence unit is defined by using one or
more of the following:[81]
• Annotated managed persistence classes contained in the root of the
persistence unit (unless the exclude-unlisted-classes element is specified)
and with reference to that following is exclude-unlisted-classes xsd
<xsd:element name="exclude-unlisted-classes" type="xsd:boolean" default="true" minOccurs="0">
<xsd:annotation>
<xsd:documentation>
When set to true then only listed classes and jars will
be scanned for persistent classes, otherwise the
enclosing jar or directory will also be scanned.
Not applicable to Java SE persistence units.
</xsd:documentation>
</xsd:annotation>
Default value of <exclude-unlisted-classes> has been changed to true if you are using JPA 2 for implementation one should use <exclude-unlisted-classes/> only instead of configuration specified above.

Categories

Resources