Showing posts with label hibernate. Show all posts
Showing posts with label hibernate. Show all posts

Sunday, October 26, 2014

DIFFERENCE BETWEEN HIBERNATE FLUSH AND COMMIT

Flushing the Session simply makes the data that is currently in the session synchronized with what is in the database.
However, just because you have flushed, doesn’t mean the data can’t be rolled back.
Commit does flush the session, but it also ends the unit of work.
To summarize commit does two things,
1. Commit internally does flush
2. Ends the unit of work (makes the changes permanent).
FLUSH:
Flushing the Session simply gets the data that is currently in the session synchronized with what is in the database. However, just because you have flushed, doesn’t mean the data can’t be rolled back.
Hibernate will flush changes automatically for you:
before query executions
when a transaction is committed
Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.
COMMIT:
Commit does flush the session, but it also ends the unit of work

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,...).

Friday, May 16, 2014

Hibernate, iBatis, Java EE or other Java ORM tool

Let me take a crack at this. First of, I've written some on this subject in Using an ORM or plain SQL?. Specifically to address your points:
Learning Curve/Ease of Use
Ibatis is about SQL. If you know SQL the learning curve for ibatis is trivial. Ibatis does some things on top of SQL such as:
  • group by;
  • discriminated types; and
  • dynamic SQL.
that you'll still need to learn but the biggest hurdle is SQL.
JPA (which includes Hibernate) on the other hand tries to distance itself from SQL and present things in an object rather than a relational way. As Joel points out however, abstractions are leaky and JPA is no exception. To do JPA you'll still need to know about relational models, SQL, performance tuning of queries and so forth.
Whereas Ibatis will simply having you apply the SQL you know or are learning, JPA will require you to know something else: how to configure it (either XML or annotations). By this I mean figuring out that foreign key relationships are a relationship (one-to-one, one-to-many or many-to-many) of some kind, the type mapping, etc.
If you know SQL I would say the barrier to learning JPA is actually higher. If you don't, it's more of a mixed result with JPA allowing you to effectively defer learning SQL for a time (but it doesn't put it off indefinitely).
With JPA once you setup your entities and their relationships then other developers can simply use them and don't need to learn everything about configuring JPA. This could be an advantage but a developer will still need to know about entity managers, transaction management, managed vs unmanaged objects and so on.
It's worth noting that JPA also has its own query language (JPA-SQL), which you will need to learn whether or not you know SQL. You will find situations where JPA-SQL just can't do things that SQL can.
Productivity
This is a hard one to judge. Personally I think I'm more productive in ibatis but I'm also really comfortable with SQL. Some will argue they're way more productive with Hibernate but this is possibly due--at least in part--to unfamiliarity with SQL.
Also the productivity with JPA is deceptive because you will occasionally come across a problem with your data model or queries that takes you a half a day to a day to solve as you turn up logging and watch what SQL your JPA provider is producing and then working out the combination of settings and calls to get it to produce something that's both correct and performant.
You just don't have this kind of problem with Ibatis because you've written the SQL yourself. You test it by running the SQL inside PL/SQL Developer, SQL Server Management Studio, Navicat for MySQL or whatever. After the query is right, all you're doing is mapping inputs and outputs.
Also I found JPA-QL to be more awkward than pure SQL. You need separate tools to just run a JPA-QL query to see the results and it's something more you have to learn. I actually found this whole part of JPA rather awkward and unwieldy although some people love it.
Maintainability/Stability
The danger with Ibatis here is proliferation meaning your dev team may just keep adding value objects and queries as they need them rather than looking for reuse whereas JPA has one entitty per table and once you have that entity, that's it. Named queries tend to go on that entity so are hard to miss. Ad-hoc queries can still be repeated but I think it's less of a potential problem.
That comes at the cost of rigidity however. Often in an application you will need bits and pieces of data from different tables. With SQL it's easy because you can write a single query (or a small number of queries) to get all that data in one hit and put it in a custom value object just for that purpose.
With JPA you are moving up that logic into your business layer. Entities are basically all or nothing. Now that's not strictly true. Various JPA providers will allow you to partially load entities and so forth but even there you're talking about the same discrete entitites. If you need data from 4 tables you either need 4 entities or you need to combine the data you want into some kind of custom value object in the business or presentation layer.
One other thing I like about ibatis is that all your SQL is external (in XML files). Some will cite this is as a disadvantage but not me. You can then find uses of a table and/or column relatively easy by searching your XML files. With SQL embedded in code (or where there is no SQL at all) it can be a lot harder to find. You can also cut and paste SQL into a database tool and run it. I can't overstate enough how many times this has been useful to me over the years.
Performance/Scalability
Here I think ibatis wins hands down. It's straight SQL and low cost. By its nature JPA simply won't be able to manage the same level of latency or throughput. Now what JPA has going for it is that latency and throughput are only rarely problems. High performance systems however do exist and will tend to disfavour more heavyweight solutions like JPA.
Plus with ibatis you can write a query that returns exactly the data you want with the exact columns that you need. Fundamentally there's no way JPA can beat (or even match) that when it's returning discrete entities.
Ease of Troubleshooting
I think this one is a win for Ibatis too. Like I mentioned above, with JPA you will sometimes spend half a day getting a query or entity produce the SQL you want or diagnosing a problem where a transaction fails because the entity manager tried to persist an unmanaged object (which could be part of a batch job where you've committed a lot of work so it might be nontrivial to find).
Both of them will fail if you try to use a table or column that doesn't exist, which is good.
Other criteria
Now you didn't mention portability as one of your requirements (meaning moving between database vendors). It's worth noting that here JPA has the advantage. The annotations are less portable than, say, Hibernate XML (eg standard JPA annotations don't have an equivalent for Hibernate's "native" ID type) but both of them are more portable than ibatis / SQL.
Also I've seen JPA / Hibernate used as a form of portable DDL, meaning you run a small Java program that creates the database schema from JPA configuration. With ibatis you'll need a script for each supported database.
The downside of portability is that JPA is, in some ways, lowest common denominator, meaning the supported behaviour is largely the common supported behaviour across a wide range of database vendors. If you want to use Oracle Analytics in ibatis, no problem. In JPA? Well, that's a problem.

Tuesday, May 13, 2014

Difference between commit and flush in Hibernate

Commit will make the database commit
- Flushing is the process of synchronizing the underlying persistent
store with persistable state held in memory.
ie. it will update or insert into your tables in the running
transaction, but it _may_ not commit those changes (this depends on
your flush mode). When you have a persisted object and you change a
value on it, it becomes dirty and hibernate needs to flush these
changes to your persistence layer. It may do this automatically for
you or you may need to do this manually, that depends on your flush
mode, check http://www.hibernate.org/hib_docs/v3/api/org/hibernate/FlushMode.html
for further details on which flush mode is the right one for you.

http://www.coderanch.com/t/218534/ORM/databases/Difference-commit-flush-Hibernate

Monday, May 5, 2014

Exclude catalog name from reverse-engineered Java classes

Guys I figured it out on how to exclude the catalog field. 

As stated before I added a property in my hibernate.cfg.xml as 

MyDatabaseName 

And also I added the hibernate.reveng.xml and used it to control the generation of pojo. I have pasted the hibernate.reveng.xml that I used 









match-schema=".*" ------> it means select any / all the schema 
match-name=".*" ------> it means select any / all the table from the schema
https://forum.hibernate.org/viewtopic.php?f=6&t=984597

Can't execute a simple HQL query from Hibernate Tools

When I generated the domain code and the hbm files from my database using Hibernate Tools, the catalog property was set for all my mapping files, so when I execute a query the generated SQL looks for bd.bd.table instead of bd.table.
So I removed the catalog property from all my mapping files
<hibernate-mapping>
<class name="beans.Famille" table="famille">
//...
</class>
</hibernate-mapping>
and now the generated code looks like this:
HQL:
from Famille
SQL:
select
  famille0_.familleID as familleID128_,
  famille0_.libelle as libelle128_ 
 from
  bd.famille famille0_

Friday, March 14, 2014

Double-logging in Hibernate

All I can think of:
  1. Check that your log4j config doesn't have multiple appenders defined at different levels? If you have your appender attached to the org.hibernate logger, and attached again to the org.hibernate.SQL logger, then you'll see this twice (unless you turn off additivity for the lower-level logger).
  2. You don't have the hibernate.show_sql property set on your SessionFactory? That doesn't enable logging to log4j (you do that through log4j config), it just dumps to the console. If your log4j is dumping to the console too you'll see it twice. However, that looks like a log4j format log line, not the console dumps done by hibernate, so that seems unlikely. Worth mentioning though.

Thursday, September 26, 2013

Enabling log4j logging in Hibernate

Hibernate 3 has integrated with slf4j logging which demands an additional step in getting Hibernate’s log4j logs. This is important because in debug mode, Hibernate logs the SQL query strings and the bind variable values. The steps to configure for capturing the log4j logs from Hibernate are below:
1. Place log4j, slf4j-api and slf4j-log4j jars in the classpath. I am using log4j-1.2.15.jar, slf4j-api-1.5.3.jar and slf4j-log4j12-1.5.3.jarfiles.
2. Now configure the log4j.properties (or XML) file and place it in your classpath. A sample properties file content is provided below. This will print all the logs on to the console. Configure a file appender if you want the logs to be writtwen to a file.
Sample log4j.properties:

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=debug, stdout
log4j.logger.org.hibernate=debug
log4j.logger.org.springframework=debug
log4j.logger.org.hibernate.hql.ast.AST=info
log4j.logger.org.hibernate.SQL=trace
log4j.logger.org.hibernate.type= trace
log4j.logger.org.hibernate.tool.hbm2ddl=warn
log4j.logger.org.hibernate.hql=debug
log4j.logger.org.hibernate.cache=info
log4j.logger.org.hibernate.jdbc=debug

You are now good to go :) Happy logging !!

Friday, August 23, 2013

Differences Between Hibernate and JPA

Fans of the Hibernate object-relational mapping (ORM) framework will realize that the Java Persistence API (JPA) is basically a standardization of that framework. And, if you’re like me, you really haven’t given much thought to JPA, because, gee, isn’t it just a watered-down Hibernate? Maybe, maybe not. (I’m not going to get into that here and now.)
It can be useful, though (even if only politically or procedurally), to code to JPA instead of the Hibernate API. If you find yourself in that situation, you may find this compare/contrast between the two API’s to be useful:
HibernateJPA
SessionFactoryEntityManagerFactory
SessionEntityManager
sessionFactory.getCurrentSession().[method]()entityManager.[method]()
saveOrUpdate()persist()
Query.setInteger/String/Entity()Query.setParameter()
list()getResultList()
uniqueResult()getSingleResult()
uniqueResult() returns nullgetSingleResult() throws NoResultException
CriteriaQueries – yesCriteriaQueries – no
Additionally, there are a couple Hibernate-specific JPA-isms to keep in mind:
  • If the underlying JPA implementation is Hibernate, either/both annotations or/and mapping files may be used – at the same time. In such a situation, I believe the mapping files act as an override for the annotations.
  • The best of both worlds (in my mind) is to base the code (at an interface- or API-level) on JPA and its EntityManager, but to have the implementation interact with the Hibernate Session, which can be obtained by calling getDelegate() on the EntityManager.

Wednesday, August 1, 2012

JPA/Hibernate store date in UTC time zone

To the best of my knowledge, you need to put your entire java app in UTC timezone (so that hibernate will store dates in UTC), and you'll need to convert to whatever timezone desired when you display stuff (at least we do it this way).
At startup, we do:
TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));
and set the desired timezone to the DateFormat:
fmt.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"))
Hope this helps,
cheers,
mitch

http://stackoverflow.com/questions/508019/jpa-hibernate-store-date-in-utc-time-zone

Saturday, May 19, 2012

Sunday, May 13, 2012

Difference between commit and flush in Hibernate

Commit will make the database commit
- Flushing is the process of synchronizing the underlying persistent
store with persistable state held in memory.
ie. it will update or insert into your tables in the running
transaction, but it _may_ not commit those changes (this depends on
your flush mode). When you have a persisted object and you change a
value on it, it becomes dirty and hibernate needs to flush these
changes to your persistence layer. It may do this automatically for
you or you may need to do this manually, that depends on your flush
mode, check http://www.hibernate.org/hib_docs/v3/api/org/hibernate/FlushMode.html
for further details on which flush mode is the right one for you.

http://www.coderanch.com/t/218534/ORM/java/Difference-between-commit-flush-Hibernate