org.hibernate.exception.ConstraintViolationException


org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:69) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:202)at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:91)at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:86)at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:171)at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2048)at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2427)at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:51)at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:243)at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:227)at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:140)at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:296)at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:980)at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:353)at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)at struts.dao.project.budgetAnalysis.BudgetPlanningDAO.saveNewBudget(BudgetAnalysisDAO.java:428)at struts.project.budgetAnalysis.NewBudgetPlanSaveAction.execute(NewBudgetSaveAction.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:595)
Caused by: java.sql.BatchUpdateException: ORA-01400: cannot insert NULL into ("ROOT"."PROJECT_BUDGET_TEST"."APPROVED_STATUS")

at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:367)
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:8739)
at org.apache.tomcat.dbcp.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:294)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:58)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:195)
... 36 more

Solution:

This type of problems generally occurs when we try to violate the constraint relationship of the tables.
The fallowing cases may be the reason for the above exception:
1)If the user try to enter null value into not null fields of the database.
2)If the user trying to store other format value into the database field.

org.hibernate.TransientObjectException


org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before
flushing: hibernate.hr.employee.EmployeeStoreValue
at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:216)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:108)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:71)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:1826)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2172)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2118)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2374)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:84)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:243)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:227)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:296)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:980)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:353)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at struts.dao.project.budgetAnalysis.BudgetAnalysisDAO.updateProjectBudget(BudgetDAO.java:574)
at struts.project.budgetAnalysis.BudgetPlanningAction.approveRejectBudgetExecute(BudgetStoringgAction.java:480)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:276)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:196)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:421)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:226)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:415)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:595)

Solution:

This type of Exception do you get generally when you try to store a null object in to the database column which has foreign key relationship with the other table column. Even if you are trying to store other column value which is not a primary key column.

Advantages of Hibernate over jdbc?


Below are the advantages of Hibernate over JDBC:

JDBC 

Hibernate 

With JDBC, developer has to write code to map an object model’s data representation to a relational data model and its corresponding database schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.
With JDBC, caching is maintained by hand-coding. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.
In JDBC there is no check that always every user has updated data. This check has to be added by the developer. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.

Other Useful Links:

Caching in Hibernate

Hibernate Interview Questions

Difference between sorted and ordered collection in hibernate

Difference between sorted and ordered collection in hibernate


Below are the differences between Sorted collection and Ordered collection in Hibernate.

sorted collection 

order collection 

A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator. Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is not large, it will be more efficient way to sort it. If your collection is very large, it will be more efficient way to sort it .

 

Other Useful Links:

Caching in Hibernate

Hibernate Interview Questions

Advantages of Hibernate over jdbc

Caching in Hibernate


Caching is a Temporary memory or buffer which resides at client side and stores the results sent by server. When client generates same request for multiple number of times, the first request generated results will be stored in cache and this result will be used across the multiple requests. This reduces the round trips between the client and server. Since the result will be collected from cache that is available at client side.

Hibernate supports for 2 levels of cache:

  1. Level one cache
  2. Level two cache.

Level One Cache:

Level 1 cache is inbuilt cache and it will be associated with hibernate session objects. Every session object of hibernate application contains one inbuilt level one cache.

Responsibilities of Level one cache:

a)      If select query executed for multiple no of times with in a session. Only one time query goes to database software gets the result, remaining all the times result will be gathered from cache.

b)      If one of pojo class object is modified for multiple no of times with in a transaction of session object, instead of sending update query for multiple number of times, all the changes done on the object wil be kept tracked and only one update query wil be generated reflecting all the changes at the end of the transaction.

The different ways to remove the level 1 cache from session

i)                    Session.flush() –>  Flushes level one cache content to db software

ii)                   Session.evict() –> Remove the content of level 1 cache

iii)                 Session.close() –> closes level 1 cache, before that it calls session.flush()

A hibernate client application can have multiple level1 caches because a hibernate application can have multiple hibernate session objects.

The data stored in level1 cache, level2 cache will be in full synchronization with table rows.

Level-2 Cache:

It is a configurable cache (Not a built in cache). Third party vendors are supplying supporting jar files for level 2 cache. Level2 cache is global cache and it is visible for all the session objects of the hibernate application.

When level-2 cache is enabled the results gathered for database software will be stored in both level 1 and level 2 caches.

sessionFactory.close() –> Destroys the session factory object and releases level 2 cache.

sessionFactory.evict(arga …) –> Removes pojo class object from session factory.

sessionFactory.evictQueries(args…) –> Cleans queries related data from cache.

If hibernate use same request as second request or different session objects then software tries to collects the results either from leve1/level2 caches.

There are different third party providers for level 2 cache:

  1. Swarm Cache
  2. OS Cache,
  3. EH Cache
  4. JBoss Tree Cache … etc.