Wednesday, September 24, 2014

JPA EntityManager: Why use persist() over merge()?

Either way will add an entity to a PersistenceContext, the difference is in what you do with the entity afterwards.
Persist takes an entity instance, adds it to the context and makes that instance managed (ie future updates to the entity will be tracked).
Merge creates a new instance of your entity, copies the state from the supplied entity, and makes the new copy managed. The instance you pass in will not be managed (any changes you make will not be part of the transaction - unless you call merge again).
Maybe a code example will help.
MyEntity e = new MyEntity();

// scenario 1
// tran starts
em.persist(e); 
e.setSomeField(someValue); 
// tran ends, and the row for someField is updated in the database

// scenario 2
// tran starts
e = new MyEntity();
em.merge(e);
e.setSomeField(anotherValue); 
// tran ends but the row for someField is not updated in the database
// (you made the changes *after* merging)

// scenario 3
// tran starts
e = new MyEntity();
MyEntity e2 = em.merge(e);
e2.setSomeField(anotherValue); 
// tran ends and the row for someField is updated
// (the changes were made to e2, not e)
Scenario 1 and 3 are roughly equivalent, but there are some situations where you'd want to use Scenario 2.

Tuesday, September 23, 2014

The Hibernate Object Life-Cycle

The Hibernate framework is used to mange the persistence of objects. It allows objects to be associated with data present in the tables. It saves/modifies and inserts records in the database tables based on values in these objects and the operations performed on them using the Hibernate interfaces.
In the sequence of these operation calls, the data objects exist in various states. These states and the transition from one state to another forms the persistence life cycle.
I picked up the diagram from the book "Java Persistence With Hibernate". It provides a very good explanation of the life cycle the objects go through as a part of their association with the Hibernate layer.
 I executed the below code to pass an object through the entire persistence life cycle:
public static void testEntityLifeCycle() {
    Entity entity = new Entity(); //new object created; in Transient state
    entity.setData("New Data 1");
    Session session = sessionFactory.openSession();
    System.out.println("Session (object is transient): " + session);
    Transaction transaction = session.beginTransaction();
    session.save(entity);// Object now in persistent state
    System.out.println("The object id is " +entity.getId());
    System.out.println("Session (after Object save): " + session);                
    transaction.commit();
    session.close();
    System.out.println("Session (after close): " + session);
    
    //here object is in detached state
    session = sessionFactory.openSession();
    session.saveOrUpdate(entity);
    //object is now in persistent state again
    System.out.println("Session (new one): " + session);
    transaction = session.beginTransaction();
    session.delete(entity);
    //the entity is now in removed state
    transaction.commit();
    System.out.println("Session (after Object deletion): " + session);
    session.close();
}// object available for garbage collection at
//end of this method
When the new Entity object is created it is in the transient state.The object is not associated with Hibernate session.
2656 [main] DEBUG org.hibernate.impl.SessionImpl  - opened session at timestamp:
 13198936161
Session (object is transient): SessionImpl(PersistenceContext[entityKeys=[],coll
ectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreat
ions=[] collectionRemovals=[] collectionUpdates=[]])
The session.save method causes Hibernate to save the object in the database table. It also assigns a primary key to the id property. The object is now in the persistent state.Persistent instances are always associated with a persistence Context.
This object is visible in the session object that is displayed after the save call. The Entity can now be seen as a part of the persistence context.
2672 [main] DEBUG org.hibernate.jdbc.JDBCContext  - after transaction begin
2687 [main] DEBUG org.hibernate.event.def.DefaultSaveOrUpdateEventListener  - sa
ving transient instance
2687 [main] DEBUG org.hibernate.event.def.AbstractSaveEventListener  - saving [c
om.model.Entity#]
2718 [main] DEBUG org.hibernate.SQL  - 
    insert 
    into
        Entity
        (DATA) 
    values
        (?)
...
The object id is 1
Session (after Object save): SessionImpl(PersistenceContext[entityKeys=[EntityKe
y[com.model.Entity#1]],collectionKeys=[]];ActionQueue[insertions=[] updates=[] d
eletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
2609 [main] DEBUG org.hibernate.transaction.JDBCTransaction  - commit
After the session is closed, the objects are removed from the session. The entity object now moves back to the detached state. It still holds persistent data, but there is no guarantee that this data will continue to be in sync with the table data. 
2781 [main] DEBUG org.hibernate.impl.SessionImpl  - closing session
...
Session (after close): SessionImpl()
It is also possible to return the object back to the persistent state.In our code we created a new session and associated the detached object to this session instance.
2781 [main] DEBUG org.hibernate.impl.SessionImpl  - opened session at timestamp:
 13198936163
2781 [main] DEBUG org.hibernate.event.def.AbstractSaveEventListener  - detached 
instance of: com.model.Entity
2781 [main] DEBUG org.hibernate.event.def.DefaultSaveOrUpdateEventListener  - up
dating detached instance
2797 [main] DEBUG org.hibernate.event.def.DefaultSaveOrUpdateEventListener  - up
dating [com.model.Entity#1]
Session (new one): SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.mode
l.Entity#1]],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] 
collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
...
2828 [main] DEBUG org.hibernate.SQL  - 
    update
        Entity 
    set
        DATA=? 
    where
        id=?
The call to delete will ensure that the object is deleted from the database table. The object now moves from the persistent state to removed state. There is no identifier associated with this object. The state of the object is similar to those in transient state.
2843 [main] DEBUG org.hibernate.SQL  - 
    delete 
    from
        Entity 
    where
        id=?
...
2843 [main] DEBUG org.hibernate.impl.SessionImpl  - after transaction completion
Session (after Object deletion): SessionImpl(PersistenceContext[entityKeys=[],co
llectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCre
ations=[] collectionRemovals=[] collectionUpdates=[]])
At the end of method, the object is now ready to be garbage collected, thus ending the persistence life-cycle of this object.
There are a lot of other methods in the diagram. There are several more methods in Hibernate which could be part of the above diagram( for r.g. Criteria methods) However we shall cover these in upcoming posts.

http://learningviacode.blogspot.com/2012/02/hibernate-object-life-cycle.html

What's the use of session.flush() in Hibernate

Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you:
  • before some query executions
  • when a transaction is committed
Allowing to explicitly flush the Session gives finer control that may be required in some circumstances (to get an ID assigned, to control the size of the Session,...).

What is the difference between identity and equality in OOP?

  • identity: a variable holds the same instance as another variable.
  • equality: two distinct objects can be used interchangeably. they often have the same id.
For example:
Integer a = new Integer(1);
Integer b = a;
a is identical to b.
Integer c =  new Integer(1);
Integer d = new Integer(1);
c is equal but not identical to d.
Of course, two identical variables are always equal.
In Java, equality is defined by the equals method. Keep in mind, if you implement equals you must also implement hashCode.

Friday, September 19, 2014

Find smallest integer value in array list in Java without Arrays.sort

This figure should be helpful :
enter image description here
Then to answer your question, what would you do on paper ?
  1. Create and initialize the min value at tenIntArray[0]
  2. Create a variable to hold the index of the min value in the array and initialize it to 0 (because we said in 1. to initialize the min at tenIntArray[0])
  3. Loop through the elements of your array
  4. If you find an element inferior than the current min, update the minimum value with this element and update the index with the corresponding index of this element
  5. You're done
Writing the algorithm should be straightforward now.

Tuesday, September 9, 2014

Java: recommended solution for deep cloning/copying an instance

for deep cloning (clones the entire object hierarchy):
  • commons-lang SerializationUtils - using serialization - if all classes are in your control and you can force implementing Serializable
  • Java Deep Cloning Library - using reflection - in cases when the classes or the objects you want to clone are out of your control (a 3rd party library) and you can't make them implement Serializable, or in cases you don't want to implement Serializable
for shallow cloning (clones only the first level properties):
I deliberately omitted the "do-it-yourself" option - the API's above provide a good control over what to and what not to clone (for example using transient, or String[] ignoreProperties), so reinventing the wheel isn't preferred.

Thursday, September 4, 2014

Displaying CLOB Column with 4000+ characters

I guess you could display the chunks as seperate rows ?
SELECT ROWNUM as chunk_no,ID, SUBSTR (t1.clob_col, (ROWNUM-1)*4000, 4000) AS chunk
FROM t1
CONNECT BY (ROWNUM-1)*4000 <= LENGTH(t1.clob_col)
or if there is a constraint on the maximum size a clob could be in you system you could hard code the number of text columns returned
SELECT SUBSTR (t1.clob_col, 1, 4000) AS pt1,
       CASE WHEN LENGTH (t1.clob_col) > 4000  THEN SUBSTR (t1.clob_col, 4001, 4000) END AS pt2,
       CASE WHEN LENGTH (t1.clob_col) > 8000  THEN SUBSTR (t1.clob_col, 8001, 4000) END AS pt3,
       CASE WHEN LENGTH (t1.clob_col) > 12000 THEN SUBSTR (t1.clob_col, 1201, 4000) END AS pt4
FROM t1
http://stackoverflow.com/questions/7357999/displaying-clob-column-with-4000-characters