Showing posts with label JPA. Show all posts
Showing posts with label JPA. Show all posts

Saturday, December 31, 2016

Eclipselink Cache Coordination with JBoss and JMS

Agenda:
  1. Creating JPA project and generating entities.
  2. Configuring persistence properties and JPA project
  3. Testing the JPA project
  4. Update database when entity changed.
  5. Setting up load balance database connection.
  6. Setting Cache Coordination in Eclipselink

Cache Coordination enables EclipseLink to synchronize data changes in a distributed environment. for more information about cache coordination in EclipseLink, click here.

Following are the steps to enable Cache Coordination in JBoss AS7 / JBoss EAP6.
1. create JMS topic

2. creaet JMS connection factory

3. add the cache coordination properties into persistence.xml
<property name="eclipselink.cache.coordination.protocol" value="jms" />

<property name="eclipselink.cache.coordination.jms.topic" value="jms/EclipseLinkTopic" />

<property name="eclipselink.cache.coordination.jms.factory" value="jms/EclipseLinkTopicConnectionFactory" />

<property name="eclipselink.cache.coordination.jms.reuse-topic-publisher" value="true" />

<property name="eclipselink.cache.coordination.jms.host" value="remote://HOST:PORT" />

4. in eclipseLink module.xml, add the following into <dependencies />
<module name="javax.jms.api"/>

5. in hornetq module.xml, add the following into <dependencies />
<module name="org.eclipse.persistence"/>



Done!!

Saturday, October 24, 2015

Complex Native SQL to JPA entity

Assuming there is a ContactDetail entity.
This could be a database table or table view.


@Entity public class ContactDetail {     private String name;     private String address;     private String phoneNo;     private String mobileNo;     private String email;     // getter and setter
}

the direct way to get this entity is to execute the following sql.

select name, address, phone_no, mobile_no, email from contact_detail;

another way is to select those column from different tables. 
eg. 

select p.name as name, a.address as address, b.phoneNo as phoneNo, b.mobileNo as mobileNo, c.email as email from person p join address a on a.p_id = p.p_id join phone b on b.p_id = p.p_id join email c on c.p_id = p.p_id;

where the entity columns are actually come from different table. 
which could be a view. 
or SQL to return a table entity based on business requirement.

after gotten the correct SQL, we can proceed to query the JPA with the native SQL.

List<ContactDetail > customers = (List<ContactDetail>)em.createNativeQuery(YOUR_NATIVE_SQL, ContactDetail.class).getResultList();


Done!!

Wednesday, August 6, 2014

Soft Delete with JPA and EclipseLink

Assuming I have the following table.

And my entity
@Entity
@Table(name="ITEM")
public class Item {
    private Long itemId;
    private String itemName;
    private Integer itemStatus;

    // getter and setter
}

for AUDITING purpose, hard delete is not encouraged.
thus, when deleting a record, the ITEM_STAUS changes to 2 (deleted).

and I have the following status code
0 - active
1 - inactive
2 - deleted

Tuesday, February 25, 2014

How to programmatically clear the JPA cache

When I used my JPA with EclipseLink as the implementation together with JBoss AS7.1.1.
I'm facing some issues.

One of the issue is the JPA cache not refresh by itself. 

Scenario:
When a new entity inserted into DB with JPA (EclipseLink).
and the new record is verified already inserted into database.

Then immediately I made a SELECT ALL query to this entity.
=> SELECT a FROM ENTITY a

But unfortunately, the newly inserted record is not appeared in the search result. 

to resolve this issue, I used the following line code the clear the JPA cached entities.


// the clear the entire JPA cache
entityManager.getEntityManagerFactory().getCache().evictAll();


// clear only selected entity from the JPA cache
entityManager.getEntityManagerFactory().getCache().evict(ENTITY.class);



Done!!

Wednesday, February 19, 2014

Case insensitive JPQL

There is no case insensitive comparison in SQL.
Thus, to write a case insensitive SQL, we have to first change the both parameter and value to same case.

The same concept is apply to JPQL as well.

below is the example of case insensitive JPQL.

String caseInsensitiveJPQL = " SELECT a FROM ENTITY a "

caseInsensitiveJPQL += " WHERE UPPER(a.PARAM1) = '" + value1.toUpperCase() "' ";


in the above example, I convert both PARAM1 and value1 to upper case.


Done!!

Wednesday, January 1, 2014

EclipseLink Static weaving with Ant

<?xml version="1.0"?>
<!DOCTYPE project>

<project name="staticWeaving" default="weaving">  

<target name="define.task"
description="New task definition for EclipseLink static weaving" >
<taskdef
name="weave"
classname="org.eclipse.persistence.tools.weaving.jpa.StaticWeaveAntTask">
<classpath refid="project.class.path" />
</taskdef>
</target>

<target name="weaving" description="perform weaving." depends="define.task">
<weave
source="original-jpa.jar"
target="weaved-jpa.jar"
persistenceinfo="${jpaProjectHome}\classes">
<classpath refid="project.class.path" />
</weave>
</target>

<path id="project.class.path">
   <pathelement path="eclipselink.jar/"/>
  <pathelement path="hibernate-jpa-2.0-api-1.0.1.Final.jar"/>
</path>

</project>

Monday, April 29, 2013

JPA Boolean Conversion

In some cases, we might want to store Boolean value in database as "Y/N" or "T/F" instead of "1/0".
This is to increase human readability and better support across different databases because different databases could store Boolean value in different data types.

JPA does support the "Y/N" or "T/F" as Boolean value with the help of @ObjectTypeConverter annotation.
We just need to annotate the entity class with this annotation.
@Entity
@ObjectTypeConverter(...)
public class MyEntity {
    ............................
    ............................
}

Example below shows the converter to convert "Y/N" to Boolean (true/false).
All 5 attributes are occupied, now what we need to do is simply provide values to all the attributes.
@ObjectTypeConverter(
    name = "YNBooleanConverter",
    dataType = String.class,
    objectType = Boolean.class,
    defaultObjectValue = "false",
    conversionValues = {
        @ConversionValue(dataValue = "Y", objectValue = "true"),
        @ConversionValue(dataValue = "N", objectValue = "false") })


Done!!

How to update database schema when JPA entity changes

  4. Update database when entity changed.
  5. Setting up load balance database connection.
  6. Setting Cache Coordination in Eclipselink

It is always changes on database tables' fields during development.
For normal approach, we probably update the database schema first and follow by the entity (both are manual process).

Now, there could be alternative by JPA provider (either Hibernate or EclipseLink).
When the JPA provider detected change(s) on entities, it will update database schema to compliance with the working copy of entities.

What we need to do is only configure to JPA provider in persistence.xml

Saturday, April 27, 2013

How to test a newly setup JPA project

  3. Testing the JPA project 

The purpose of this post is to show how to test a JPA project whether it is properly setup.
Besides, this solution can be used to test a newly created/generated entity as well.

The concept is quite simple, simply create a java class with main(String[] args), in the main method, create database connection and then execute a select statement.
If successfully select records from database, that's mean the JPA project is properly setup.

Steps:
1. Create a new package called test in the project.
2. Create a new class called JpaTest in the test package.
3. Write the following codes in the main(String[] args) to test.
    factory = Persistence.createEntityManagerFactory("HelloJPA");
    EntityManager em = factory.createEntityManager();
    Query q = em.createQuery("select a from Ofuser a");
    List<Ofuser> users = q.getResultList();   

    System.out.println("Number of users: " + users.size());
    if(users.size() > 0) {
        for (Ofuser user : users) {
            System.out.println(user);
        }       
    }

Thursday, April 25, 2013

How to configure JPA project


This post shows how to configure the JPA project about its' persistence properties after entities successfully generated in a JPA project.

Before we start to configure our JPA project, first we must decide which JPA implementation to use.
There are two(2) popular JPA implementations, which are EclipseLink and Hibernate.

Once the preferred JPA implementation installed, then we can start to configure the persistence properties.

Steps:

1. Install JPA implementation library

1.1 EclipseLink

      a) download the required EclipseLink library, and the version that I used in this tutorial is 2.4.1

      b) unzip the archive

      c) copy the javax.persistence_2.0.4.v201112161009.jar and eclipselink.jar to a folder (eg, c:\eclipselink-lib)

Monday, March 18, 2013

How to order child collection in JPA

Assume there are 2 entities, Parent and Child
In many cases, children collection are directly retrieve from parent entity without writing additional query.
But there is a problem to retrieve children collection directly from parent entity -- the children collection are in an unsorted manner.
This problem could be solved by adding the @OrderBy annotation.

@Entity 
public class Parent {
    @oneToMany

    private Set<Child> children;

    // More attributes
}

@Entity
public class Child {
    @ManyToOne    
    private Parent parent;    
        
        //More attributes
}

Saturday, December 15, 2012

JPQL IN clause

There are two ways to write IN clause in JPQL

1. conventional way
    Pass in a comma separated String into the query 
 
    StringBuffer jpql = new StringBuffer();
    jpql.append("SELECT a FROM TABLE_A a");
    jpql.append("WHERE a.id IN (:idList)");
    Query query = entityManager.createQuery(jpql.toString());
    query.setParameter("idList", idList);
        in this case, idList is a comma separated string, eg. "1, 2, 3, 4"

How to generate entities from tables with Eclipse JPA Tools


The purpose of this post is to show detail steps on how to setting up JPA project and generate entities for the JPA Project

Required Software/Tool
1. Eclipse
2. JDBC jar file for the target database

LinkWithin

Related Posts Plugin for WordPress, Blogger...