JPA2 with HBase datastore using Datanucleus writing duplicate rows - java

I'm creating simple java web app that writes one row of data to HBase table via JPA2 (using Datanucleus) everything working except it writing 2 duplicate rows instead of just writing 1 row
Results
ROW COLUMN+CELL
402881813acfed78013acfed78e00000 column=ACCOUNT_TABLE:FIRSTNAME, timestamp=1352108207916, value=testname
402881813acfed78013acfed78e00000 column=ACCOUNT_TABLE:ID, timestamp=1352108207916, value=402881813acfed78013acfed78e00000
402881813acfed78013acfed78e00000 column=ACCOUNT_TABLE:LASTNAME, timestamp=1352108207916, value=testname2
402881813acfed78013acfed78e00000 column=ACCOUNT_TABLE:LEVEL, timestamp=1352108207916, value=\x00\x00\x00\x03
402881813acfed78013acfedf7e20001 column=ACCOUNT_TABLE:FIRSTNAME, timestamp=1352108210172, value=testname
402881813acfed78013acfedf7e20001 column=ACCOUNT_TABLE:ID, timestamp=1352108210172, value=402881813acfed78013acfedf7e20001
402881813acfed78013acfedf7e20001 column=ACCOUNT_TABLE:LASTNAME, timestamp=1352108210172, value=testname2
402881813acfed78013acfedf7e20001 column=ACCOUNT_TABLE:LEVEL, timestamp=1352108210172, value=\x00\x00\x00\x03
2 row(s) in 0.1270 seconds
Datanucleus version in pom.xml
<org.datanucleus-version>3.1.1</org.datanucleus-version>
dependencies in pom.xml
<dependencies>
<!-- JPA 2.0 Spec -->
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jpa_2.0_spec</artifactId>
<version>1.1</version>
</dependency>
<!-- JDO API -->
<dependency>
<groupId>javax.jdo</groupId>
<artifactId>jdo-api</artifactId>
<version>3.0</version>
</dependency>
<!-- DataNucleus HBase -->
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-hbase</artifactId>
<version>${org.datanucleus-version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-core</artifactId>
<version>1.0.4</version>
<exclusions>
<exclusion>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
</exclusion>
<exclusion>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase</artifactId>
<version>0.94.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.3</version>
</dependency>
<!-- DataNucleus Core -->
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>${org.datanucleus-version}</version>
<scope>runtime</scope>
</dependency>
<!-- DataNucleus Enhancer -->
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-enhancer</artifactId>
<version>${org.datanucleus-version}</version>
</dependency>
<!-- DataNucleus JPA api -->
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-api-jpa</artifactId>
<version>${org.datanucleus-version}</version>
</dependency>
Plugin in pom.xml
<plugin>
<groupId>org.datanucleus</groupId>
<artifactId>maven-datanucleus-plugin</artifactId>
<version>${org.datanucleus-version}</version>
<configuration>
<api>JPA</api>
<log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>
<verbose>true</verbose>
<persistenceUnitName>hbase-test</persistenceUnitName>
</configuration>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
Account.java
package org.test.model;
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name = "ACCOUNT_TABLE")
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ACCOUNT_TABLE:ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private String id;
#Column(name = "ACCOUNT_TABLE:FIRSTNAME")
private String firstName;
#Column(name = "ACCOUNT_TABLE:LASTNAME")
private String lastName;
#Column(name = "ACCOUNT_TABLE:LEVEL")
private int level = 0;
public Account() {
}
public Account(String firstName, String lastName, int level) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.level = level;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
persistence.xml
<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="hbase-test" transaction-type="RESOURCE_LOCAL">
<provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
<mapping-file>org/test/model/orm.xml</mapping-file>
<class>org.test.model.Account</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="datanucleus.storeManagerType" value="hbase" />
<property name="datanucleus.ConnectionURL" value="hbase:localhost:60010"/>
<property name="datanucleus.ConnectionUserName" value=""/>
<property name="datanucleus.ConnectionPassword" value=""/>
<property name="datanucleus.autoCreateSchema" value="true"/>
<property name="datanucleus.autoCreateTables" value="true" />
<property name="datanucleus.autoCreateColumns" value="true" />
<property name="datanucleus.validateTables" value="true"/>
<property name="datanucleus.validateConstraints" value="false"/>
<property name="datanucleus.Optimistic" value="false"/>
<property name="datanucleus.Multithreaded" value="true" />
</properties>
</persistence-unit>
</persistence>
orm.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">
<description>JPA Mapping file for Test</description>
<package>org.test.model</package>
<entity class="org.test.model.Account" name="Account">
<table name="ACCOUNT_TABLE" />
<attributes>
<id name="id">
<generated-value strategy="AUTO"/>
</id>
<basic name="firstName">
<column name="ACCOUNT_TABLE:FIRSTNAME"/>
</basic>
<basic name="lastName">
<column name="ACCOUNT_TABLE:LASTNAME"/>
</basic>
<basic name="level">
<column name="ACCOUNT_TABLE:LEVEL"/>
</basic>
</attributes>
</entity>
</entity-mappings>
TestAddAccountRow.java
package org.test.app;
import org.test.model.Account;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class TestAddAccountRow {
public void addAccount() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hbase-test");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = null;
Account a2 = new Account("testname","testname2",3);
tx = em.getTransaction();
tx.begin();
em.persist(a2);
tx.commit();
}
}

UPDATE
#Datanucleus
I had code in spring mvc controller calling DAO (adding Account object), i don't know why but this was causing the duplicate rows, Datanucleus works perfectly.
While i couldn't find why it was creating duplicate rows, i swap out Datanucleus for Kundera it seems to solve the problem of duplicate rows
I think there a bug in Datanucleus
Kundera version number
<kundera-version>2.1</kundera-version>
pom.xml dependencies
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.impetus.core</groupId>
<artifactId>kundera-core</artifactId>
<version>${kundera-version}</version>
</dependency>
<dependency>
<groupId>com.impetus.client</groupId>
<artifactId>kundera-hbase</artifactId>
<version>${kundera-version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.impetus.kundera.rest</groupId>
<artifactId>kundera-rest</artifactId>
<version>${kundera-version}</version>
</dependency>
<!-- HBase and Hadoop -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-core</artifactId>
<version>1.0.4</version>
<exclusions>
<exclusion>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
</exclusion>
<exclusion>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase</artifactId>
<version>0.94.0</version>
</dependency>
persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Copyright (C) 2010 Bartosch Warzecha, Matthias Weßendorf
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<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="hbase">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<class>org.test.model.Account</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="kundera.nodes" value="localhost" />
<property name="kundera.port" value="60010" />
<property name="kundera.keyspace" value="test" />
<property name="kundera.dialect" value="hbase" />
<property name="kundera.client.lookup.class" value="com.impetus.client.hbase.HBaseClientFactory" />
<property name="kundera.cache.provider.class"
value="com.impetus.kundera.cache.ehcache.EhCacheProvider" />
<property name="kundera.cache.config.resource" value="/ehcache-test.xml" />
<property name="kundera.ddl.auto.prepare" value="create" />
</properties>
</persistence-unit>
</persistence>

Related

NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session;

I'm having some struggles since a while with Hibernate, trying to access data from my database. I searched a lot for the error and tried lots of things, just don't know what else I can't do, I tried things regarding my pom dependencies but nothing worked. Here it is:
Main class:
public class Main {
private static SessionFactory factory;
public static void main(String[] args)
{
// User u = new User();
//
// UserDAO ud=new UserDAO(new Configuration().configure().buildSessionFactory());
// ud.listUsers();
// factory = ((AnnotationConfiguration) new AnnotationConfiguration().
// configure()).
// //addPackage("com.xyz") //add package if used.
// addAnnotatedClass(User.class).
// buildSessionFactory();
factory = new Configuration().configure().buildSessionFactory();
UserDAO ud=new UserDAO(factory);
ud.listUsers();
}
}
The listUsers method:
public void listUsers( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List users = session.createQuery("FROM user").list();
for (Iterator iterator =
users.iterator(); iterator.hasNext();){
User employee = (User) iterator.next();
System.out.print("First Name: " + employee.getUsername());
System.out.print("Last Name: " + employee.getPassword());
System.out.println("Address: " + employee.getAddress());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
Config File:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/licenta
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">root</property>
<mapping resource="user.hbm.xml" />
</session-factory>
</hibernate-configuration>
User mapping:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="models.User" table="user">
<meta attribute="class-description">
This class contains the user detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native" />
</id>
<property name="username" column="username" type="string" />
<property name="password" column="password" type="string" />
<property name="address" column="address" type="string" />
<property name="email" column="email" type="string" />
<property name="phone" column="phone" type="string" />
<property name="year" column="year" type="int" />
<property name="type" column="type" type="string" />
</class>
</hibernate-mapping>
Pom file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.paul.licenta</groupId>
<artifactId>teachApp</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>teachApp</name>
<build>
<finalName>teachApp</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.0.0.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.0.GA</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- for JPA, use hibernate-entitymanager instead of hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.10.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- uncomment this to get JSON support
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
-->
</dependencies>
<properties>
<jersey.version>2.26-b03</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Error:
Exception in thread "main" java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session;
at dao.UserDAO.listUsers(UserDAO.java:58)
at Main.main(Main.java:31)
Also, if you look, in the main method, I have 2 instances of factory object, one is commented. If I uncomment that one and comment the 2nd one, it gaves me the same error.
Any suggestions?
Here is everything the console shows at running
Imports from UserDAO class:
import java.util.Iterator;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import models.User;
import net.sf.ehcache.hibernate.HibernateUtil;
Imports from Main Class:
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import dao.UserDAO;
import models.User;
Your import of Session class is wrong, use import org.hibernate.Session ,instead of org.hibernate.classic.Session.

How can i use named queries in JPA without having to list the entity in persistence.xml?

I am able to retrieve and persist an Entity without listing it in persistence.xml, but if I want to use a #NamedQuery, it doesn't work unless I list it in persistence.xml. Is there a way around this?
I am using Tomcat 8 with OpenJPA 2.4.2.
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">
<!-- Used for persisting events, authentication pieces -->
<persistence-unit name="PushPersistence" transaction-type="RESOURCE_LOCAL">
<!-- Use Apache's OpenJPA -->
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<!-- Our backing store is our data source from context.xml -->
<non-jta-data-source>java:comp/env/jdbc/webservice</non-jta-data-source>
<!--
Without this, I can load and persist the entity but
CANNOT use Named Queries
-->
<class>push.authentication.AuthCredentials</class>
<!-- Don't require listing the managed classes here -->
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="openjpa.DynamicEnhancementAgent" value="true"/>
<property name="openjpa.RuntimeUnenhancedClasses" value="supported"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
<property name="openjpa.ConnectionFactoryProperties" value="PrettyPrint=true, PrettyPrintLineLength=72, PrintParameters=true, MaxActive=10, MaxIdle=5, MinIdle=2, MaxWait=60000"/>
</properties>
</persistence-unit>
</persistence>
Maven:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>MyProj</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<!-- Tell Maven what language version to use -->
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.enterprise/cdi-api -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
</dependency>
<!-- Enables the annotations, etc needed -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<exclusions>
<exclusion>
<groupId>javax.exterprise</groupId>
<artifactId>cdi-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Our jersey libs -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.25.1</version>
</dependency>
<!-- CDI to JAX-RS Binding -->
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.containers.glassfish/jersey-gf-cdi-ban-custom-hk2-binding -->
<dependency>
<groupId>org.glassfish.jersey.containers.glassfish</groupId>
<artifactId>jersey-gf-cdi</artifactId>
<version>2.14</version>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.weld.servlet/weld-servlet-core -->
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet-core</artifactId>
<version>3.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.weld/weld-core-impl -->
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-core-impl</artifactId>
<version>3.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<version>2.4.2</version>
</dependency>
</dependencies>
<build>
<!-- We don't use the version number in the war file name -->
<finalName>MyProj</finalName>
<plugins>
<!-- Enhances the JPA classes -->
<plugin>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<version>2.4.2</version>
<executions>
<execution>
<id>JPA Enhance</id>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
<configuration>
<includes>**/push/*.class</includes>
<persistenceXmlFile>${project.basedir}/src/main/resources/META-INF/persistence.xml</persistenceXmlFile>
<toolProperties>
<property>
<name>addDefaultConstructor</name>
<value>false</value>
</property>
<property>
<name>enforcePropertyRestrictions</name>
<value>true</value>
</property>
</toolProperties>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Class declaration of named query:
package push;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Base64;
import java.util.Date;
#Entity
#NamedQueries(
{
#NamedQuery(
name = "Users.findByName",
query = "SELECT ac FROM Users ac WHERE ac.userName = :userName"
)
}
)
#Table(name = "PushClient")
public class Users
{
...
}
I read the EntityManager Interface and it says it throws IllegalArgumentException if a query has not been defined with the given name or if the query string is found to be invalid or if the query result is found to not be assignable to the specified type and if get IllegalArgumentException based on your snippet of code I think the third one is your case, try to use
EntityManager.createNamedQuery(java.lang.String name);
instead of
EntityManager.createNamedQuery(java.lang.String name,
java.lang.Class<T> resultClass);
And see if you get the same result or not

persistance.xml doesn't create database in Intellij

I faced a really big problem with creating database using persistent.xml . Ok, i start from the beginning.
I created a maven (artifact ->webapp) project. I added a META-INF directory with file persistence.xml into my source directory like that:
<?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="myDatabase" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/Lab6" />
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
</properties>
</persistence-unit>
</persistence>
Then i put some model into my java sources. I added apropiate annotations like that:
package model;
import javax.persistence.*;
#Entity
#Table(name="author")
public class Author
{
private int Id;
private String firstName;
private String lastName;
#Id
#Column(name = "id", nullable = false)
#GeneratedValue(strategy= GenerationType.SEQUENCE, generator="seq")
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
#Column(name = "first_name", nullable = false)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "last_name", nullable = false)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
After this I added a servlet class to connect to let the program make some operations using POST method. Nevermind :) After that I run the project and ... nothing hapened; program run successfully, I can get into servlet but database hadnt been created. Then I started to search the solution on a web and nothing helped my with my problem. Below is my pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Lab6</groupId>
<artifactId>Lab6</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Lab6 Maven Webapp</name>
<url>http://maven.apache.org</url>
<build>
<finalName>Lab6</finalName>
<testResources>
<testResource>
<directory>src/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>net.java.dev.glassfish</groupId>
<artifactId>glassfish-persistence-api</artifactId>
<version>b32g</version>
</dependency>
</dependencies>
</project>
I really stuck. Until now i checked other versions of providers (eclipse) in persistence.xml, and made some really weird changes inside that file but without success. I was checking also war file. Every needed file were inside (especcially persistence.xml). FI change my current glassfish version of server to different ones but it didnt help :(((
Reeally guys please help me with that. My knowlage is ropably too low to have better ideas ghow to fix that
Thanks in advance
You are missing the part of persistence.xml that tells it how to find your classes. Here are a couple options:
<jar-file>MyLibrary.jar</jar-file>
<class>model.Author</class>
Which option you choose will depend on how your project is set up.

Hibernate 3 not auto creating tables

Here is my code:
hiberntae.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>edu.bc.eagleapps</groupId>
<artifactId>mavenproject1</artifactId>
<version>1.2-SNAPSHOT</version>
<packaging>war</packaging>
<name>mavenproject1</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>4.0.6.RELEASE</springframework.version>
<hibernate.version>3.6.9.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.2-GA</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-base</artifactId>
<version>2.6.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>6.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Model
package app.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="USER_MASTER")
public class UserMaster {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private String id;
#Column(length = 50, nullable = false, unique = true)
private String userid;
#Column(length = 50, nullable = false, unique = true)
private String password;
public UserMaster() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
When I try to save user via controller, I get the following error:
org.hibernate.exception.SQLGrammarException: could not insert: [app.model.UserMaster]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at coolcook.dao.UserMasterDao.saveUser(UserMasterDao.java:23)
at coolcook.service.UserMasterServiceImpl.saveUser(UserMasterServiceImpl.java:16)
at coolcook.controller.UserController.registerUser(UserController.java:28)
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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
a
t java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'app.USER_MASTER' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
the database "app" exists, but whenever I try to save user through controller, it gives me above error.
I search through several answers on SO and other sites but not successful. Any help will be appreciated!
Dao
package coolcook.dao;
import coolcook.model.UserMaster;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class UserMasterDao {
#Autowired
private SessionFactory sessionFactory;
public UserMaster saveUser(UserMaster user) {
Session session = sessionFactory.openSession();
Transaction tx = null;
Integer employeeID = null;
try {
tx = session.beginTransaction();
session.save(user);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return user;
}
}
springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="app" />
<!--<mvc:resources mapping="/views/**" location="/views/" />-->
<mvc:default-servlet-handler />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/app" p:username="root"
p:password="root" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>app.model</value>
</list>
</property>
<property name="configLocation">
<value>WEB-INF/hibernate.cfg.xml</value>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<context:annotation-config />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/views/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
dependancies can be a culprit as because of conflict. In my case, exclusion of dom4j solved the issue. Try updating jackson dependency in your pom.xml. It worked for me.
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-base</artifactId>
<version>2.6.3</version>
<exclusions>
<exclusion>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</exclusion>
</exclusions>
</dependency>
You have defined hibernate.hbm2ddl.auto as create. This sometimes gives this error because each time your application runs, your table is deleted.
Try changing this to validate.
validate: validate that the schema matches, make no changes to the
schema of the database.
<property name="hibernate.hbm2ddl.auto">validate</property>
your hibernate and spring config file add this property <prop key="hibernate.hbm2ddl.auto">update</prop> ; for example:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
p:dataSource-ref="dataSource">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>

TCP Idle connections growing on Azure Web App

I have a mobile application which connects to Azure web services written in Spring Hibernate which communicates to Azure SQL server for performing data operations.
In hibernate we dont have any connection manager configured. We are using Hibernate sessionFactory for managing the connections.
Recently after too many users using the app, we found that the Azure automatically restarting the services after reaching the max connection limits of Azure which is 1920 TCP connections.
TCP connections once used either go into CLOSE_WAIT state or TIME_WAIT state.
They are not properly closing the connections.
Is this related to some Azure VM Server not closing the connections or has to do with the Java coding style used.
Pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mastek</groupId>
<artifactId>transaction-rs</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>transaction-rs</name>
<properties>
<springframework.version>4.0.6.RELEASE</springframework.version>
<hibernate.version>4.3.6.Final</hibernate.version>
<sqlserver.version>4.0</sqlserver.version>
<swagger-version>1.3.0</swagger-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- MS SQL server driver -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>${sqlserver.version}</version>
</dependency>
<!-- orika mapper -->
<dependency>
<groupId>ma.glasnost.orika</groupId>
<artifactId>orika-core</artifactId>
<version>1.4.6</version>
</dependency>
<!-- resteasy api -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>3.0.13.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>3.0.13.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.13.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>3.0.13.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-spring</artifactId>
<version>3.0.13.Final</version>
</dependency>
<!-- Resteasy Servlet Container Initializer -->
<!-- scope 'provided' for JBoss AS -->
<!-- <dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-servlet-initializer</artifactId>
<version>3.0.11.Final</version>
<scope>compile</scope>
</dependency> -->
<!-- slf4j and logger -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.1</version>
</dependency>
<!-- swagger for documentation -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jaxrs</artifactId>
<version>1.5.0</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<!-- commons -->
<dependency>
<groupId>com.mastek.commons</groupId>
<artifactId>commons</artifactId>
<version>1.0</version>
</dependency>
<!-- JSON to XML -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
<!-- Gson: Java to Json conversion -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.2</version>
<scope>compile</scope>
</dependency>
<!-- swagger start -->
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-jaxrs_2.9.1</artifactId>
<version>${swagger-version}</version>
</dependency>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-annotations_2.9.1</artifactId>
<version>${swagger-version}</version>
</dependency>
<!-- swagger end -->
</dependencies>
<build>
<finalName>transaction-rs</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Persistence-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:property-placeholder ignore-resource-not-found="true" location="file:/sdt/configuration/services.properties, file:../../sdt/configuration/services.properties, classpath:application.properties" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${transaction.service.jdbc.driverClassName}" />
<property name="url" value="${transaction.service.jdbc.url}"/>
<property name="username" value="${transaction.service.jdbc.username}" />
<property name="password" value="${transaction.service.jdbc.password}"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<list>
<value>com.mastek.commons.data.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
This is the part of my DAOImpl.java:
package com.mastek.security.data.service;
import static com.mastek.commons.util.ApplicationConstants.DELIMITER;
import static com.mastek.commons.util.ApplicationConstants.END;
import static com.mastek.commons.util.ApplicationConstants.GET_WEEK;
import static com.mastek.commons.util.ApplicationConstants.REGISTER_USER;
import static com.mastek.commons.util.ApplicationConstants.START;
import static com.mastek.commons.util.ApplicationConstants.USER_ID;
import static com.mastek.commons.util.ApplicationConstants.VEFIFY_USER;
import static com.mastek.commons.util.ApplicationConstants.GET_USER_BY_EMAIL;
import java.util.Date;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.mastek.commons.data.dao.impl.AbstractDAO;
import com.mastek.commons.data.entity.VWLoginUser;
import com.mastek.commons.data.entity.VWUser;
import com.mastek.commons.data.entity.VWWeekEnding;
import com.mastek.commons.domain.UserDO;
import com.mastek.commons.domain.WeekDO;
import com.mastek.commons.exception.DataStoreException;
import com.mastek.commons.exception.SystemException;
import com.mastek.commons.util.CommonUtil;
import ma.glasnost.orika.MapperFacade;
/**
* The Class RegistrationDAOImpl.
*/
#Repository
public class RegistrationDAOImpl extends AbstractDAO implements RegistrationDAO
{
/** The Constant logger. */
private static final Logger logger = LoggerFactory.getLogger(RegistrationDAOImpl.class);
/** The mapper facade. */
#Autowired
private MapperFacade mapperFacade;
/**
* This method verifies logged in user.
*
* #param surname the surname
* #param userId the user id
* #return the user do
* #throws DataStoreException the data store exception
*/
#Override
public UserDO verifyUser(String surname, long userId) throws DataStoreException
{
logger.info(VEFIFY_USER + DELIMITER + USER_ID + userId + DELIMITER + START);
UserDO userDO = null;
Session session = openSession();
try
{
Query query = session.getNamedQuery("VWLoginUser.getUser");
query.setLong("userId", userId);
query.setString("surname", surname);
VWLoginUser user = (VWLoginUser) query.uniqueResult();
userDO = mapperFacade.map(user, UserDO.class);
}
catch (org.hibernate.exception.DataException de)
{
logger.error(VEFIFY_USER + DELIMITER + USER_ID + userId + DELIMITER + SystemException.Type.DE.getErrorCode() + DELIMITER + SystemException.Type.DE.getMessage());
logger.error(VEFIFY_USER, de);
throw new DataStoreException(new SystemException(SystemException.Type.DE, de));
}
catch (org.hibernate.exception.JDBCConnectionException jdbcce)
{
logger.error(VEFIFY_USER + DELIMITER + USER_ID + userId + DELIMITER + SystemException.Type.JDBCCE.getErrorCode() + DELIMITER + SystemException.Type.JDBCCE.getMessage());
logger.error(VEFIFY_USER, jdbcce);
throw new DataStoreException(new SystemException(SystemException.Type.JDBCCE, jdbcce));
}
catch (org.hibernate.exception.SQLGrammarException sqlge)
{
logger.error(VEFIFY_USER + DELIMITER + USER_ID + userId + DELIMITER + SystemException.Type.SQLGE.getErrorCode() + DELIMITER + SystemException.Type.SQLGE.getMessage());
logger.error(VEFIFY_USER, sqlge);
throw new DataStoreException(new SystemException(SystemException.Type.SQLGE, sqlge));
}
finally
{
session.clear();
session.close();
}
logger.info(VEFIFY_USER + DELIMITER + USER_ID + userId + DELIMITER + END);
return userDO;
}
}
This is my AbstractDAO.java:
package com.mastek.commons.data.dao.impl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
* The Class AbstractDAO.
*/
public abstract class AbstractDAO
{
/** The session factory. */
#Autowired
private SessionFactory sessionFactory;
/**
* Gets the session.
*
* #return the session
*/
protected Session getSession()
{
return sessionFactory.getCurrentSession();
}
/**
* Open session.
*
* #return the session
*/
protected Session openSession()
{
Session session = sessionFactory.openSession();
return session;
}
/**
* Persist.
*
* #param entity the entity
*/
public void persist(Object entity)
{
getSession().persist(entity);
}
/**
* Delete.
*
* #param entity the entity
*/
public void delete(Object entity)
{
getSession().delete(entity);
}
/**
* Gets the session factory.
*
* #return the session factory
*/
public SessionFactory getSessionFactory()
{
return sessionFactory;
}
/**
* Sets the session factory.
*
* #param sessionFactory the session factory
*/
public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
}

Categories

Resources