Skip to main content

Hibernate Annotations & Serializable Interface



Why Hibernate entities needs to implement serializable interface do we really need it always or for some scenarios.???

As per oracle docs
"If an entity instance be passed by value as a detached object, such as through a session bean’s remote business interface, the class must implement the Serializable interface."

So its look like it is required in some scenarios but its not mandatory.So may be we take it as a best practice so it would be compatible to use all scenarios. There could be scenarios where we may have to pass JPA pojo or Entity as a value holder object from one layer to another to avoid use of DTO's (Data Transfer object). Which we use by copy & pass the data to next layers.  Some time we may need to pass them over Http layers as a session object may be from presentation layer to business layer. So its content need to be serializable. So we reached on conclusion that its better is most of cases to implement serializable marker interface.

why we have 2 types of annotations in hibernate.First which starts from javax.persistence.* & another one which are like org.hibernate.annotations.* ??????

So one type is JPA based which are javax.persistence & another one is Hibernate based which are org.hibernate.annotations. Hibernate take advantage from JPA annotations as they are applicable in all JPA compliant ORM tools.One more point is JPA annotations are basic one & hibernation annotations are providing extra feature.So one should first with JPA & if required should move towards Hibernate annotations.

JPA Basic annotations: 

@Entityimport javax.persistence.Entity;
@Tableimport javax.persistence.Table;
@Columnimport javax.persistence.Column;
@Idimport javax.persistence.Id;
@GeneratedValueimport javax.persistence.GeneratedValue;
@Versionimport javax.persistence.Version;
@OrderByimport javax.persistence.OrderBy;
@Transientimport javax.persistence.Transient;
@Lobimport javax.persistence.Lob;

JPA Mapping annotations 

@OneToOneimport javax.persistence.OneToOne;
@ManyToOneimport javax.persistence.ManyToOne;
@OneToManyimport javax.persistence.OneToMany;
@ManyToManyimport javax.persistence.ManyToMany;
@PrimaryKeyJoinColumnimport javax.persistence.PrimaryKeyJoinColumn;
@JoinColumnimport javax.persistence.JoinColumn;
@JoinTableimport javax.persistence.JoinTable;
@MapsIdimport javax.persistence.MapsId;


JAP inheritance annotations

@Inheritanceimport javax.persistence.Inheritance;
@DiscriminatorColumnimport javax.persistence.DiscriminatorColumn;
@DiscriminatorValueimport javax.persistence.DiscriminatorValue;



While above JPA basic annotations is good to be used in simple application Hibernate annotations are present for some advanced user or applications.


Hibernate annotations for Queries

@org.hibernate.annotations.NamedQuery
@org.hibernate.annotations.NamedQueries,
@org.hibernate.annotations.NamedNativeQuery
 @org.hibernate.annotations.NamedNativeQueries

As a Query Hints

org.hibernate.cacheableWhether the query should interact with the second level cache (defualt to false);
org.hibernate.cacheRegionCache region name (default used otherwise)
org.hibernate.timeoutQuery timeout
org.hibernate.fetchSizeresultset fetch size
org.hibernate.flushModeFlush mode used for this query
org.hibernate.cacheModeCache mode used for this query
org.hibernate.readOnlyEntities loaded by this query should be in read only mode or not (default to false)
org.hibernate.commentQuery comment added to the generated SQL



Hibernate annotations for Runtime filters 

@org.hibernate.annotations.FilterDef or @FilterDefs define filter definition(s) used by filter(s) using the same name. A filter definition has a name() and an array of parameters(). A parameter will allow you to adjust the behavior of the filter at runtime
@FilterDef(name="minLength", parameters=@ParamDef( name="minLength", type="integer" ) )
@Filters( {
    @Filter(name="betweenLength", condition=":minLength <= length and :maxLength >= length"),
    @Filter(name="minLength", condition=":minLength <= length")
} )


annotaions for Custom SQL for CRUD operations

@SQLInsert@SQLUpdate@SQLDelete@SQLDeleteAll respectively override the INSERT statement, UPDATE statement, DELETE statement, DELETE statement to remove all entities.

annotations for Fetch profiles

@Entity
@FetchProfile(name = "customer-with-orders", fetchOverrides = {
   @FetchProfile.FetchOverride(entity = Customer.class, association = "orders", mode = FetchMode.JOIN)
})
public class Customer {
   @Id
   @GeneratedValue
   private long id;
   private String name;
   private long customerNumber;
   @OneToMany
   private Set<Order> orders
}



There are other modules of hibernate exist where other annotations available. 
Hibernate Validator
Hibernate search 
Hibernate Entity Manager
Hibernate Shards
Hibernate tools




Comments

Popular posts from this blog

Conversion from Clob To String in java and Vice versa

/***reading Clob data from oracle table and setting to Pojo**/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import oracle.sql.CLOB;

import com.poc.one.pojo.StagedMessage;

public class MessageDao {
private static String url = "jdbc:oracle:thin:@172.22.22.198:1521:ORACLE";
private static String username = "ABC123";
private static String password = "ABC123";


public  List readClobToBO() throws Exception {

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement stmt = conn
.prepareStatement("SELECT ID, STORE_ID, MESSAGE_DATA FROM STAGED_MESSAGE ");
ResultSet resultSet = stmt.executeQuery();
List msgList= new ArrayList();

while (resultSet.next()) {

StagedMessage message = new StagedMessage();

message.setId(resultSet.getInt(1));
message.setStoreId(r…

Portable Java 8/ JDK8 setup without admin rights

Some time we got machine to work where we don't have access rights to install anything or if you do not want to install. You can get latest jdk running by this trick. Just follow step step & do comment if you like it.

Step by Step details to get running java from .exe setup without any admin rights. Get portable 7 zip from portableapps.comdownload java 8 from oracle  http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.htmlopen 7 zip & extract jdk-8u102-windows-x64.exeyou will see below folders                .data                .pdata                .rdata                .reloc                .rsrc                .text                CERTIFICATE

          5.Go inside E:\jdk-8u102-windows-x64\.rsrc\1033\JAVA_CAB10you will find 111 file.

         6.extract it it some folder where you can find tools.zip again extract that to some folder say Java & copy it to very first folder of setup along with .data,.rsrc etc.
         7.Go to folder where you have co…

Multi Threading , Producer consumer problem in Java

Multi threading is topic which is always fascinating for java developer. I feel its more about practical the theory. So here i wanted to present sample examples which clear understanding for several multi threading concept.

In Theory basically thread which is light weight process.Thread shares mostly same memory space.
I said mostly because there is some space called thread local which is not common to threads & separate for each thread. We create thread whenever we wanted to use multicore of processor although that doesn't mean single core cant use it. In single core context switching works among different running thread.

for example suppose there is website which is showing latest price as well as offer as well as doing order booking all these things can be assigned to different thread to provide parallel processing.



There are 2 ways for creating a thread.

Extend a thread & Implement a Runnable class. Extending a class is little avoided since it closed possibility for e…