Friday, September 26, 2014

java: how for loop work in the case of BigInteger

You use these syntax instead:
BigInteger i = BigInteger.valueOf(100000L);  // long i = 100000L;
i.compareTo(BigInteger.ONE) > 0              // i > 1
i = i.subtract(BigInteger.ONE)               // i = i - 1
So here's an example of putting it together:
    for (BigInteger bi = BigInteger.valueOf(5);
            bi.compareTo(BigInteger.ZERO) > 0;
            bi = bi.subtract(BigInteger.ONE)) {

        System.out.println(bi);
    }
    // prints "5", "4", "3", "2", "1"
Note that using BigInteger as a loop index is highly atypical. long is usually enough for this purpose.

API links


The compareTo idiom

From the documentation:
This method is provided in preference to individual methods for each of the six boolean comparison operators (<==>>=!=<=). The suggested idiom for performing these comparisons is: (x.compareTo(y)0), where  is one of the six comparison operators.
In other words, given BigInteger x, y, these are the comparison idioms:
x.compareTo(y) <  0     // x <  y
x.compareTo(y) <= 0     // x <= y
x.compareTo(y) != 0     // x != y
x.compareTo(y) == 0     // x == y
x.compareTo(y) >  0     // x >  y
x.compareTo(y) >= 0     // x >= y
This is not specific to BigInteger; this is applicable to any Comparable in general.

Note on immutability

BigInteger, like String, is an immutable object. Beginners tend to make the following mistake:
String s = "  hello  ";
s.trim(); // doesn't "work"!!!

BigInteger bi = BigInteger.valueOf(5);
bi.add(BigInteger.ONE); // doesn't "work"!!!
Since they're immutable, these methods don't mutate the objects they're invoked on, but instead return new objects, the results of those operations. Thus, the correct usage is something like:
s = s.trim();
bi = bi.add(BigInteger.ONE);
http://stackoverflow.com/questions/3024186/java-how-for-loop-work-in-the-case-of-biginteger

Thursday, September 25, 2014

Difference between save and saveOrUpdate method hibernate

save
Save method stores an object into the database. It will Persist the given transient instance, first assigning a generated identifier. It returns the id of the entity created.
Whereas,
SaveOrUpdate()
Calls either save() or update() on the basis of identifier exists or not. e.g if identifier exists, save()will be called or else update() will be called.
There are many more like persist(), merge(), saveOrUpdateCopy(). Almost all are same giving slight different functionality and usability.

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.