Wednesday, March 18, 2015

Entity and Value Object and Embedding multiple objects

There are two type of objects in hibernate.
1. Entity
2. Value Objects

Entity
--------
Entity objects basically can stand alone without depending on another.
eg: College, Student

Value Objects
-----------------
Object which cannot standalone and does not have a clear meaning when taken alone. These type of objects has meaning only when they are presented with an Entity Object. In other words these objects add a meaning / value to Entity objects.
eg: Address - address will add a  value to Student or College.

Hibernate gives @Embeddable  annotation to embed the value object to Entity.

Steps to embed
-------------------
1. annotate value object with @Embeddable .
   eg : Address annotate with @Embeddable

2. Define a reference to value object inside Entity.Annotate the reference/ field with @Embedded.
Note: Even though you did not annotate the reference with @Embedded , still value object will embed in to Entity. The table entries for Value Object will be created inside Entity object's table.
Address object's field values will be created inside Studet/College or UserDetails table.
 eg :

@Embedded
private Address address;


Entity

@Entity
@Table(name = "USER_DETAILS")
public class UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "USER_ID")
private int userId;
@Basic
private String userName;

@Temporal(TemporalType.TIMESTAMP)
private Date joinDate;
@Transient
private String notInTable;
@Embedded
private Address address;

@Lob
private String description;

public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public Date getJoinDate() {
return joinDate;
}

public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}

public String getNotInTable() {
return notInTable;
}

public void setNotInTable(String notInTable) {
this.notInTable = notInTable;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

@Override
public String toString() {
return "UserDetails [userId=" + userId + ", userName=" + userName
+ ", joinDate=" + joinDate + ", notInTable=" + notInTable
+ ", address=" + address + ", description=" + description + "]";
}
}

Value Objects
-------

@Embeddable
public class Address {
private String street;
private String city;
private String state;
private String pincode;

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getPincode() {
return pincode;
}

public void setPincode(String pincode) {
this.pincode = pincode;
}

@Override
public String toString() {
return "Address [street=" + street + ", city=" + city + ", state="
+ state + ", pincode=" + pincode + "]";
}


}


Table : user_Details

USER_ID,description,joinDate,userName,city,pincode,state,street
--------------------------------------------------------------------------------------
5,"FU description","2015-03-18 11:04:08","First User",fCity,fPincode,fstate,fstreet
6,"FU description","2015-03-18 11:05:38","First User",fCity,fPincode,fstate,fstreet

Note: I have not defined column names for Embedded object and thus it will create columns with corresponding field names.

So let's give the names for columns
in hibernate configuration file ( hibernate.cfg.xml ) property for gbm2ddl is set as update
<property name="hbm2ddl.auto">create

So when we give the names for columns, it will create new set of columns and enter the values inside USER_DETAIL  table.

public class Address {
@Column(name="STREET_NAME")
private String street;
@Column(name="CITY_NAME")
private String city;
@Column(name="STATE_NAME")
private String state;
@Column(name="PINCODE")
private String pincode;

......getter and setters
}

Table entries

USER_ID,description,joinDate,userName,city,pincode,state,street,CITY_NAME,STATE_NAME,STREET_NAME
-------------------------------------------------------
9,"FU description","2015-03-18 12:43:40","FirstUser",fCity,fPincode,fstate,fstreet,NULL,NULL,NULL
10,"FU description","2015-03-18 12:46:07","FirstUser",NULL,fPincode,NULL,NULL,fCity,fstate,fstreet


As you can see above new columns created with name CITY_NAME,STATE_NAME,STREET_NAME
No new column created for pincode as name has not been changed.

Previous columns has null values.

So if needed to get rid of old columns , all you have to do is to change "hbm2ddl" property value to "create"
But then it will drop the previous schema and create a brand new table and enter values. You will lose old data.

USER_ID,CITY_NAME,PINCODE,STATE_NAME,STREET_NAME,description,joinDate,userName
1,fCity,fPincode,fstate,fstreet,"FU description","2015-03-18 13:04:22","First User"


test class as below
----------------------
import java.util.Date;

import org.dom4j.util.UserDataElement;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import dto.user.Address;
import dto.user.UserDetails;

public class hibernate {
public static void main(String[] args) {
UserDetails user = new UserDetails();
// user.setUserId(1);
user.setUserName("First User");
user.setJoinDate(new Date());
user.setDescription("FU description");

Address address = new Address();
address.setCity("fCity");
address.setPincode("fPincode");
address.setState("fstate");
address.setStreet("fstreet");

user.setAddress(address);
// create session factory - one object- get session from SessionFactory
// need configuration to build sessionFactory
// new Configuration().configure()
// u need to have hibernate.cfg.xml in default place resources

SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();

// retrieve object

user = null;
session = sessionFactory.openSession();
session.beginTransaction();
user = (UserDetails) session.get(UserDetails.class, 1);
System.out.println(user);
}
}


---------------------------------------------------

Now we have a problem. That is If you need to have more than one value object of same type in Entity.
ie: two addresses, homeAddress and officeAddress

       @Embedded
private Address homeAddress;
@Embedded
private Address officeAddress;

You can try to save the object. It will definitely give an error where address table columns will be duplicated. You cannot have two columns in the same name. Columns should be unique. Error will happen when second address columns comes.

------------ error will be as below -----------------------------

Exception in thread "main" org.hibernate.MappingException: Repeated column in mapping for entity: dto.user.UserDetails column: CITY_NAME (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:709)
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:731)
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:727)
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:753)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:506)
at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1360)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1851)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
at hibernate.main(hibernate.java:39)

----------------------------------------------------------------


Answer:

How to overcome this issue in the Embedded objects. Hibernate has given option to override.
We have two annotations
@AttributeOverride =  override the name of a column
@AttributeOverrides =  group override columns to embed object

So we have to give the override names with @AttributeOverride to each attribute/ field in the address table , and finally all @AttributeOverride  definitions must be grouped inside @AttributeOverrides.

So when wrtting the annotation , best thing is write the
@AttributeOverrides   and then write @AttributeOverride inside it one by one for each attribute in the address/ value object with comma (,) seperated within the braces as shown below.

@AttributeOverride  will have atleast
 * name of the attribute we are going to rename , in value object (street)
 * name of the column in the table

So going into the example we will have

@Embedded
@AttributeOverrides({ 
@AttributeOverride(name = "street", column = @Column(name = "HOME_STREET_NAME")) ,
@AttributeOverride(name="city", column=@Column(name="HOME_STREET_NAME")),
@AttributeOverride(name="state", column=@Column(name="HOME_STREET_NAME")),
@AttributeOverride(name="pincode", column=@Column(name="HOME_STREET_NAME"))
})
private Address homeAddress;


Note : As per our example we are using only two address object and giving override values for either homeAddress or OfficeAddress is enough as other object will have table column names with default address attribute defiend column names.
Annotation will be written in the Entity object (UserDetails)

eg : here if we give override values for only honeAddress as shown above then we will have table entries

-------------------------

USER_ID,description,HOME_CITY_NAME,HOME_PINCODE,HOME_STATE_NAME,HOME_STREET_NAME,joinDate,CITY_NAME,PINCODE,STATE_NAME,STREET_NAME,userName
--------------------------------------------------------------------------------------------------------
1,"FU description",hCity,hPincode,hstate,hstreet,
"2015-03-18 13:51:42",oCity,oPincode,ostate,ostreet,"First User"

-----------------------------------------

But it is always better to give attribute override definition to both value objects. home address and office address.

So new code will be as follows

Address.java
----------------------

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class Address {
@Column(name="STREET_NAME")
private String street;
@Column(name="CITY_NAME")
private String city;
@Column(name="STATE_NAME")
private String state;
@Column(name="PINCODE")
private String pincode;

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getPincode() {
return pincode;
}

public void setPincode(String pincode) {
this.pincode = pincode;
}

@Override
public String toString() {
return "Address [street=" + street + ", city=" + city + ", state="
+ state + ", pincode=" + pincode + "]";
}


}


--------------------------------------------------------

UserDetails.java
-----------------------------------------------------------

import java.util.Date;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

@Entity
@Table(name = "USER_DETAILS")
public class UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "USER_ID")
private int userId;
@Basic
private String userName;

@Temporal(TemporalType.TIMESTAMP)
private Date joinDate;
@Transient
private String notInTable;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "street", column = @Column(name = "HOME_STREET_NAME")),
@AttributeOverride(name = "city", column = @Column(name = "HOME_CITY_NAME")),
@AttributeOverride(name = "state", column = @Column(name = "HOME_STATE_NAME")),
@AttributeOverride(name = "pincode", column = @Column(name = "HOME_PINCODE")) })
private Address homeAddress;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "street", column = @Column(name = "OFFICE_STREET_NAME")),
@AttributeOverride(name = "city", column = @Column(name = "OFFICE_CITY_NAME")),
@AttributeOverride(name = "state", column = @Column(name = "OFFICE_STATE_NAME")),
@AttributeOverride(name = "pincode", column = @Column(name = "OFFICE_PINCODE")) })
private Address officeAddress;

@Lob
private String description;

public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public Date getJoinDate() {
return joinDate;
}

public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}

public String getNotInTable() {
return notInTable;
}

public void setNotInTable(String notInTable) {
this.notInTable = notInTable;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public Address getHomeAddress() {
return homeAddress;
}

public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}

public Address getOfficeAddress() {
return officeAddress;
}

public void setOfficeAddress(Address officeAddress) {
this.officeAddress = officeAddress;
}

@Override
public String toString() {
return "UserDetails [userId=" + userId + ", userName=" + userName
+ ", joinDate=" + joinDate + ", notInTable=" + notInTable
+ ", homeAddress=" + homeAddress + ", officeAddress="
+ officeAddress + ", description=" + description + "]";
}
}


----------------------------

test class
hibernateT.java


-----------------------------------------------------

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import dto.user.Address;
import dto.user.UserDetails;

public class hibernate {
public static void main(String[] args) {
UserDetails user = new UserDetails();
// user.setUserId(1);
user.setUserName("First User");
user.setJoinDate(new Date());
user.setDescription("FU description");

Address homeAddress = new Address();
homeAddress.setCity("hCity");
homeAddress.setPincode("hPincode");
homeAddress.setState("hstate");
homeAddress.setStreet("hstreet");

Address officeAddress = new Address();
officeAddress.setCity("oCity");
officeAddress.setPincode("oPincode");
officeAddress.setState("ostate");
officeAddress.setStreet("ostreet");

user.setHomeAddress(homeAddress);
user.setOfficeAddress(officeAddress);
// create session factory - one object- get session from SessionFactory
// need configuration to build sessionFactory
// new Configuration().configure()
// u need to have hibernate.cfg.xml in default place resources

SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();

// retrieve object

user = null;
session = sessionFactory.openSession();
session.beginTransaction();
user = (UserDetails) session.get(UserDetails.class, 1);
System.out.println(user);
}
}

---------------------------------------

output
------------------------------------

INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists USER_DETAILS
Hibernate: create table USER_DETAILS (USER_ID integer not null auto_increment, description longtext, HOME_CITY_NAME varchar(255), HOME_PINCODE varchar(255), HOME_STATE_NAME varchar(255), HOME_STREET_NAME varchar(255), joinDate datetime, OFFICE_CITY_NAME varchar(255), OFFICE_PINCODE varchar(255), OFFICE_STATE_NAME varchar(255), OFFICE_STREET_NAME varchar(255), userName varchar(255), primary key (USER_ID))
Mar 18, 2015 1:59:43 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into USER_DETAILS (description, HOME_CITY_NAME, HOME_PINCODE, HOME_STATE_NAME, HOME_STREET_NAME, joinDate, OFFICE_CITY_NAME, OFFICE_PINCODE, OFFICE_STATE_NAME, OFFICE_STREET_NAME, userName) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: select userdetail0_.USER_ID as USER_ID1_0_0_, userdetail0_.description as descript2_0_0_, userdetail0_.HOME_CITY_NAME as HOME_CIT3_0_0_, userdetail0_.HOME_PINCODE as HOME_PIN4_0_0_, userdetail0_.HOME_STATE_NAME as HOME_STA5_0_0_, userdetail0_.HOME_STREET_NAME as HOME_STR6_0_0_, userdetail0_.joinDate as joinDate7_0_0_, userdetail0_.OFFICE_CITY_NAME as OFFICE_C8_0_0_, userdetail0_.OFFICE_PINCODE as OFFICE_P9_0_0_, userdetail0_.OFFICE_STATE_NAME as OFFICE_10_0_0_, userdetail0_.OFFICE_STREET_NAME as OFFICE_11_0_0_, userdetail0_.userName as userNam12_0_0_ from USER_DETAILS userdetail0_ where userdetail0_.USER_ID=?
UserDetails [userId=1, userName=First User, joinDate=2015-03-18 13:59:42.0, notInTable=null, homeAddress=Address [street=hstreet, city=hCity, state=hstate, pincode=hPincode], officeAddress=Address [street=ostreet, city=oCity, state=ostate, pincode=oPincode], description=FU description]


---------------------------------------------------------

Table Entries = user_Details

--------------------------------------------------------------

USER_ID,description,HOME_CITY_NAME,HOME_PINCODE,HOME_STATE_NAME,HOME_STREET_NAME,joinDate,OFFICE_CITY_NAME,OFFICE_PINCODE,OFFICE_STATE_NAME,OFFICE_STREET_NAME,userName
--------------------------------------------
1,"FU description",hCity,hPincode,hstate,hstreet,"2015-03-18 13:59:42",oCity,oPincode,ostate,ostreet,"First User"


Problem 3:
How to make embedded object as primary key

Let's say we have a value object LoginName and we want to make this as a primary key for UserDetail.

So let's change userName of type int to LoginName

before change;;
--------

        @Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "USER_ID")
private int userId;

----

Note : 
Now we can't use @Id , we have convert this to @EmbeddedId and have to remove column definition also. cause LoginName will have few fields.

New 
--------

@EmbeddedId
private LoginName userId;

Note : making LoginName class @Embeddable is optional

@Embeddable
public class LoginName implements Serializable {

}


Final code for Embedded primary key
-----------------------------------------------------

Address.java  - no change

UserDetails.java 

change primary key type int to LoginName
remove annotation and changed to @EmbeddedId

------------------------------------------------------------------------
import java.util.Date;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

@Entity
@Table(name = "USER_DETAILS")
public class UserDetails {

@EmbeddedId
private LoginName userId;
@Basic
private String userName;

@Temporal(TemporalType.TIMESTAMP)
private Date joinDate;
@Transient
private String notInTable;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "street", column = @Column(name = "HOME_STREET_NAME")),
@AttributeOverride(name = "city", column = @Column(name = "HOME_CITY_NAME")),
@AttributeOverride(name = "state", column = @Column(name = "HOME_STATE_NAME")),
@AttributeOverride(name = "pincode", column = @Column(name = "HOME_PINCODE")) })
private Address homeAddress;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "street", column = @Column(name = "OFFICE_STREET_NAME")),
@AttributeOverride(name = "city", column = @Column(name = "OFFICE_CITY_NAME")),
@AttributeOverride(name = "state", column = @Column(name = "OFFICE_STATE_NAME")),
@AttributeOverride(name = "pincode", column = @Column(name = "OFFICE_PINCODE")) })
private Address officeAddress;

@Lob
private String description;

public LoginName getUserId() {
return userId;
}

public void setUserId(LoginName userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public Date getJoinDate() {
return joinDate;
}

public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}

public String getNotInTable() {
return notInTable;
}

public void setNotInTable(String notInTable) {
this.notInTable = notInTable;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public Address getHomeAddress() {
return homeAddress;
}

public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}

public Address getOfficeAddress() {
return officeAddress;
}

public void setOfficeAddress(Address officeAddress) {
this.officeAddress = officeAddress;
}

@Override
public String toString() {
return "UserDetails [userId=" + userId + ", userName=" + userName
+ ", joinDate=" + joinDate + ", notInTable=" + notInTable
+ ", homeAddress=" + homeAddress + ", officeAddress="
+ officeAddress + ", description=" + description + "]";
}
}
---------------------------------------------------------------------------------------------------

LoginName.java  - newly created , implements Serializable
Note : @Embeddable is optional, as we mention @EmbeddedId  in the UserDetails.java 

@EmbeddedId
private LoginName userId;


----------------------------------------------------------------------------------------------------

import javax.persistence.Embeddable;

@Embeddable
public class LoginName implements Serializable {

/**
* 
*/
private static final long serialVersionUID = -121704761597041786L;
private String firstName;
private String lastname;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

}



----------------------------------------------------------------------------------------------------
Test code

----------------------------------------------------------------------------------------------------
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import dto.user.Address;
import dto.user.LoginName;
import dto.user.UserDetails;

public class hibernate {
public static void main(String[] args) {
UserDetails user = new UserDetails();
// user.setUserId(1);
LoginName loginName = new LoginName();
loginName.setFirstName("firstName1");
loginName.setLastname("lastname");
user.setUserId(loginName);
user.setUserName("First User");
user.setJoinDate(new Date());
user.setDescription("FU description");

Address homeAddress = new Address();
homeAddress.setCity("hCity");
homeAddress.setPincode("hPincode");
homeAddress.setState("hstate");
homeAddress.setStreet("hstreet");

Address officeAddress = new Address();
officeAddress.setCity("oCity");
officeAddress.setPincode("oPincode");
officeAddress.setState("ostate");
officeAddress.setStreet("ostreet");

user.setHomeAddress(homeAddress);
user.setOfficeAddress(officeAddress);
// create session factory - one object- get session from SessionFactory
// need configuration to build sessionFactory
// new Configuration().configure()
// u need to have hibernate.cfg.xml in default place resources

SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();

// retrieve object

user = null;
session = sessionFactory.openSession();
session.beginTransaction();
// user = (UserDetails) session.get(UserDetails.class, 1);
// System.out.println(user);
}
}


----------------------------------------------------------------------------------------------------
output for update

----------------------------------------------------------------------------------------------------

INFO: HHH000232: Schema update complete
Hibernate: insert into USER_DETAILS (description, HOME_CITY_NAME, HOME_PINCODE, HOME_STATE_NAME, HOME_STREET_NAME, joinDate, OFFICE_CITY_NAME, OFFICE_PINCODE, OFFICE_STATE_NAME, OFFICE_STREET_NAME, userName, firstName, lastname) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)



output for create - create new schema
-------------

INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists USER_DETAILS
Hibernate: create table USER_DETAILS (firstName varchar(255) not null, lastname varchar(255) not null, description longtext, HOME_CITY_NAME varchar(255), HOME_PINCODE varchar(255), HOME_STATE_NAME varchar(255), HOME_STREET_NAME varchar(255), joinDate datetime, OFFICE_CITY_NAME varchar(255), OFFICE_PINCODE varchar(255), OFFICE_STATE_NAME varchar(255), OFFICE_STREET_NAME varchar(255), userName varchar(255), primary key (firstName, lastname))
Mar 18, 2015 4:15:54 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into USER_DETAILS (description, HOME_CITY_NAME, HOME_PINCODE, HOME_STATE_NAME, HOME_STREET_NAME, joinDate, OFFICE_CITY_NAME, OFFICE_PINCODE, OFFICE_STATE_NAME, OFFICE_STREET_NAME, userName, firstName, lastname) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)



----------------------------------------------------------------------------------------------------



Errors which can come making value object as primary key

1. embedded object as primary key , composite key as primary key not implementing serializable
---------------------------------------------------

Exception in thread "main" org.hibernate.MappingException: Composite-id class must implement Serializable: dto.user.LoginName
at org.hibernate.mapping.RootClass.checkCompositeIdentifier(RootClass.java:290)
at org.hibernate.mapping.RootClass.validate(RootClass.java:279)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1360)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1851)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
at hibernate.main(hibernate.java:45)

Problem: LoginName.java has not implemented Serializable
Solution : implements Serializable

@Embeddable
public class LoginName implements Serializable {

}

2. Duplicate key
--------------------

As we are using composite key, the combination of the fields in the embedded object must be unique.
 eg : Our LoginName include two fields. firstName and lastName. The value combination of first name and last name must be unique.

So if you try to enter same values for first name and last name, you will get duplicate key violation

--------------------------------------------

Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:465)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:351)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at hibernate.main(hibernate.java:49)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'firstName-lastname' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2643)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2280)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2265)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 13 more

-------------------------------------------------------------------------

.

3. Null id generation for Embedded key
----------
Here as for example Entity class "UserDetails.java" we have defined @EmbeddedId " LoginName userId;"
when saving system need to generate the id for UserDetails  object.
So in generating id, UserDetails object needs the details of the LoginName object.
If LoginName details are not provided, LoginName object detail is null
LoginName = null
, then UserDetails object cannot generate id., EmbeddedId


--------------------------------------------
Exception in thread "main" org.hibernate.id.IdentifierGenerationException: null id generated for:class dto.user.UserDetails
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:119)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at hibernate.main(hibernate.java:48)

----------------------------------------

solution :
provide details for LoginName when creating UserDetails object and save

               UserDetails user = new UserDetails();

                LoginName loginName = new LoginName();
loginName.setFirstName("firstName");
loginName.setLastname("lastname");
user.setUserId(loginName);


 4. Constraint violation

This is same as above,( LoginName userId  become null , / or not set -  when not set default will be null)

when generating embedded key and also as defined value object as embedded key, the fields/ or attributes values cannot be null.

you must set the values for the userId ( object of the LoginName), the first name and last name.

-----------------------------------------

WARN: Column 'lastname' cannot be null
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:465)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:351)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at hibernate.main(hibernate.java:49)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'firstName' cannot be null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2643)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2280)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2265)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 13 more

------------------------------------------------

solution : same as solution for above - create loginName  object and set the unique combination set of values for first name and last name.

                LoginName loginName = new LoginName();
loginName.setFirstName("firstName");
loginName.setLastname("lastname");
user.setUserId(loginName);








Tuesday, March 17, 2015

Natural key vs Surrogate key

This is very common in primary key selection.
Let's take an example to have a better understanding and for ease of explaining.

if we take list of people, for more precisely take students.
So we have student list. every student has a email. thus email cannot be duplicate. So we can use email as a unique identifier for a student. In a scenario like this email is a natural key for student.

Surrogate key on the other hand does not have any relevance to the business and but where need to have a unique key to identify the object, we define surrogate key.
eg : serial number, id for any table(student_id, group_id)

When we have Surrogate key we have problem of maintaining uniqueness.
Hibernate has given solution, actually made our lives easy with making sure hibernate layer generate unique ids.
eg : User object has user_id as primary key

@Id
@GeneratedValue
private int userId;

this will take care of the surrogate key , userId and generarate unique value for userId.

Further hibernate has given us the option of using a strategy for generated value.


@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "USER_ID")
private int userId;

we have 4 strategy types

GenerationType.AUTO = either identity column, sequence or table depending on the underlying DB
GenerationType.IDENTITY=  identity column
GenerationType.SEQUENCE =  sequence
GenerationType.TABLE - hibernate will make a separate table and use that.table holding the id

http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-identifier


Creating Applications with hibernate. Few things to remember

hibernate.cfg.xml configuration file.
------------------------

<?xml version="1.0" encoding="utf-8"?gt;
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"gt;
<hibernate-configurationgt;
<session-factorygt;
<property name="hibernate.bytecode.use_reflection_optimizer"gt;false</propertygt;
<property name="hibernate.connection.driver_class"gt;com.mysql.jdbc.Driver</propertygt;
<property name="hibernate.connection.password"gt;root123</propertygt;
<property name="hibernate.connection.url"gt;jdbc:mysql://localhost:3306/test1</propertygt;
<property name="hibernate.connection.username"gt;root</propertygt;
<property name="hibernate.dialect"gt;org.hibernate.dialect.MySQLDialect</propertygt;
<property name="show_sql"gt;true</propertygt;

<!-- drop and recreate databse on startup --gt;
<!-- <property name="hbm2ddl.auto"gt;create</propertygt; --gt;
<property name="hbm2ddl.auto"gt;create</propertygt;

<!-- dto classes annotated --gt;
<!-- previously <mapping resource="com/common/Stock.hbm.xml"gt;</mappinggt; --gt;
<!-- if you do not have class the u have to comment --gt;
<!-- <mapping class="com.common.Stock"gt;</mappinggt; --gt;
<mapping class="dto.user.UserDetails"gt;</mappinggt;
</session-factorygt;
</hibernate-configurationgt;

1. <property name="hbm2ddl.auto"gt;create</propertygt;

this will create schema every time code runs.
It's better to use this when you want to create the db schema for first time after that use "update"

2. entering mapping files , dto

make sure you have class file/ java files with names given with class name. Other wise it will lead to
org.hibernate.MappingException: Unable to load class
<mapping class="dto.user.ClassName"gt;</mappinggt;

-------------------------
the dto file

@Entity(name="USER_DETAILS")
public class UserDetails {

@Id
@Column(name="USER_ID")
private int userId;
@Column(name="USER_NAME")
private String userName;

public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

}

---------------

3. @Entity - maps to table
if you need to specify name for entity and this will name for table.
Else if needed to have Entity and Table different names then use @Table

@Entity
@Table(name="USER_DETAILS")
public class UserDetails {

4. You need to have a primary key for table, @Id is the primary key
5. @Column = this will create columns with given name. If you have not specified(this annotation is optional and without column annotation table column names will be names corresponding to DTO field name) table column will be the field name eg: userId and userName
as we have metioned columns will be USER_ID, USER_NAME respectively.

-----------
In simple below is more than enough. Thus create table name= UserDetails  with two columns userId,userName making userId as primany Key.

@Entity
public class UserDetails {

@Id

private int userId;

private String userName;

public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

}

6. Note: where Annotation is used.
you can use annotation in the getter or field.
Above I have used in the filed. Let's look at what gone a happen if used in getter.
To check that, I have added a check string for user name +" with Getter"




@Entity
@Table(name="USER_DETAILS")
public class UserDetails {


private int userId;

private String userName;
@Id
@Column(name="USER_ID")
public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}
@Column(name="USER_NAME")
public String getUserName() {
return userName +" with Getter";
}

public void setUserName(String userName) {
this.userName = userName;
}

}

This will add the above mentioned string to user name at each records

select * from user_Details;
USER_ID |    USER_NAME
1               |  First User with Getter

If you use Field, then field
 Note : Do not use both field and getter
I have tried. I put  
@Id
@Column(name="USER_ID") above field,
that and out put was similar to annotation over field, where check string was not appended.

7. If you do not want to add a filed to table, use @Transient

8. @Basic

9. date and time
Here "joinDate" we have not  mentioned anything, it will default map to timeStamp
result will be

joinDate
------------
2015-03-17 15:39:46

you have other options

a.) @Temporal(TemporalType.DATE)
private Date joinDate;

joinDate
------------
2015-03-17

b.) @Temporal(TemporalType.TIME)
private Date joinDate;

joinDate
------------
15:45:29

c.) @Temporal(TemporalType.TIMESTAMP)
       private Date joinDate;


joinDate
------------
2015-03-17 15:46:27



10. @Lob
this is for large String, byte stream
Mysql this mapped to "longText"

depend on situation you might have CLOB- character or BLOB - byte stream









Some Exceptions coming while Create Maven project with hibernate

Below i am describing some of the exceptions and error which might come while you are trying to build project with hibernate annotation.

In maven i have used below dependency



 
 
   org.hibernate
   hibernate-core
   4.3.8.Final
 

 
   org.hibernate
   hibernate-annotations
   3.5.6-Final
 

 
   org.hibernate
   hibernate-commons-annotations
   3.3.0.ga
 
 
 
   junit
   junit
   4.8.1
 




we have created dto class UserDetails.java (dto.user.UserDetails)

below is the hibernate.cfg.xml configuration file.



"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">


  false
  com.mysql.jdbc.Driver
  root123
  jdbc:mysql://localhost:3306/test1
  root
  org.hibernate.dialect.MySQLDialect
  true

 
  create

 
 
 
 
 





If you can see above, we have include "com.common.Stock" for mapping and we have not defined this class in the project. So this will lead to below error.
Before that below is our test code

------
public class hibernate {
 public static void main(String[] args) {
  UserDetails user = new UserDetails();
  user.setUserId(1);
  user.setUserName("First User");
  // create session factory - one object- get session from SessionFactory
  // need configuration to build sessionFactory
  // new Configuration().configure()
  // u need to have hibernate.cfg.xml in default place resources

  SessionFactory sessionFactory = new Configuration().configure()
    .buildSessionFactory();
  Session session = sessionFactory.openSession();
  session.beginTransaction();
  session.save(user);
  session.getTransaction().commit();
  session.close();
 }
}

-------------------------------

Exception in thread "main" org.hibernate.MappingException: Unable to load class [ com.common.Stock] declared in Hibernate configuration entry
 at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2281)
 at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2229)
 at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2209)
 at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2162)
 at org.hibernate.cfg.Configuration.configure(Configuration.java:2077)
 at org.hibernate.cfg.Configuration.configure(Configuration.java:2056)
 at hibernate.main(hibernate.java:17)
Caused by: java.lang.ClassNotFoundException: com.common.Stock
 at java.net.URLClassLoader$1.run(Unknown Source)
 at java.net.URLClassLoader$1.run(Unknown Source)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(Unknown Source)
 at java.lang.ClassLoader.loadClass(Unknown Source)
 at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
 at java.lang.ClassLoader.loadClass(Unknown Source)
 at java.lang.Class.forName0(Native Method)
 at java.lang.Class.forName(Unknown Source)
 at org.hibernate.internal.util.ReflectHelper.classForName(ReflectHelper.java:193)
 at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2278)
 ... 6 more
--------------------------------------

As you have not defined you should either remove from hibernate configuration class or comment that. Best is remove.

---
2. Error number 2 : missing of driver class for Mysql

If you can look at the above mentioned dependencies, I have not included a driver for Mysql. This will give below error.

Exception in thread "main" org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [com.mysql.jdbc.Driver]
 at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:243)
 at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.loadDriverIfPossible(DriverManagerConnectionProviderImpl.java:200)
 at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildCreator(DriverManagerConnectionProviderImpl.java:156)
 at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:95)
 at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
 at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
 at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
 at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
 at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
 at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
 at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
 at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
 at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
 at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
 at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
 at hibernate.main(hibernate.java:18)
Caused by: java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver
 at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:228)
 at java.lang.ClassLoader.loadClass(Unknown Source)
 at java.lang.ClassLoader.loadClass(Unknown Source)
 at java.lang.Class.forName0(Native Method)
 at java.lang.Class.forName(Unknown Source)
 at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:240)
 ... 15 more

-------------

Solution 2: Include dependency for driver:Mysql

       

  mysql
  mysql-connector-java
  5.1.9



--------------
It will work fine and you will have below out in the eclipse. Note : we have used "create"\
create where this will lead to drop exist table and create every time runs.
Table will have same name as DTO. ie: table name=Userdetails fields=userId,Username and userId will be primary

----------------------------------

Mar 17, 2015 1:38:07 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Mar 17, 2015 1:38:07 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.8.Final}
Mar 17, 2015 1:38:07 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
Mar 17, 2015 1:38:07 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Mar 17, 2015 1:38:07 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Mar 17, 2015 1:38:07 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Mar 17, 2015 1:38:07 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Mar 17, 2015 1:38:07 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Mar 17, 2015 1:38:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Mar 17, 2015 1:38:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/test1]
Mar 17, 2015 1:38:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
Mar 17, 2015 1:38:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Mar 17, 2015 1:38:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Mar 17, 2015 1:38:13 PM org.hibernate.dialect.Dialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Mar 17, 2015 1:38:13 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Mar 17, 2015 1:38:14 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Mar 17, 2015 1:38:14 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory
INFO: HHH000397: Using ASTQueryTranslatorFactory
Mar 17, 2015 1:38:17 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists UserDetails
Hibernate: create table UserDetails (userId integer not null, userName varchar(255), primary key (userId))
Mar 17, 2015 1:38:19 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into UserDetails (userName, userId) values (?, ?)




Thursday, February 19, 2015

Thread Vs Runnable

When somebody asks about thread in java, obviously anybody's answer will be..
There are two types of ways to implement Threads in Java.
1. Extends Thread class
2. Implement Runnable

Above answer is based with java 1.5 and prior versions and Threads has more better implementations with 1.5 and later versions.
I am  not going to go through those and just look at Thread class Runnable interface.

Both has common functionality. That is to facilitate programmer to write a thread or letting programmer to implement some work within a thread without worrying much about thread mechanism.

So how java let you to do your work in the thread.

Very simple. Java has given run() method.
So whatever you need to do it inside a thread or the work to be done concurrently must be implement inside run() method.

So it is very simple..

So explain in literature...  override run() method with concurrent functionality.

So if both these give override over run() method, then why we have two options.
Is it cause one is legacy and other is newer.
Answer is no.

It has more depth. It can be explained with adhere to principles like Open close principle , Liskov substitution .. etc. You can find more details about those principles on the web.

So let's go into detail analysis

First we take Thread class. We can simply create thread by Extends with Thread class. Override run() method. create instance of the class and simply call thread functionality, start() method to run the thread.

Below is an example :
MyThread class is extends Thread class.
I have included constructor with name and set the name for thread with calling super constructor method. This is optional. But with this you can set the name for thread as it creates.
Then we have run() method. This is where logic or the work of the thread resides.

In this thread I have initialized int variable , count
Inside run() method, I increment count and print the value.

So this is an implementation of a "MyThread" thread. you can test with creating instance of "MyThread"  and simply calling start() method.
----------------------------------------------------------------------------------------------------


public class MyThread extends Thread {

int count = 0;

public MyThread(String name) {
super(name);
}

@Override
public void run() {
for (int i = 0; i < 3; i++) {
count++;
System.out.println("MyThread count="+count);
}
}
}

-------------------------------------------------------------------------------------------------------

Below shows testing of MyThread  class.
I have created Compare class to test the Mythread class which will be used to compare the Runnable implementation with Thread extension.

--------------------------------------------------------------------------------------------------------
public class Compare {

public static void main(String[] args) {
MyThread t1 = new MyThread("t1");
MyThread t2 = new MyThread("t2");
MyThread t3 = new MyThread("t3");
t1.start();
t2.start();
t3.start();
}
}
-----------------------------------------------------------------------------------------------------------

Out of the Compare class as follows
-----------------------------------------------------------------------------------------------------------
MyThread count=1
MyThread count=1
MyThread count=2
MyThread count=3
MyThread count=1
MyThread count=2
MyThread count=2
MyThread count=3
MyThread count=3

-----------------------------------------------------------------------------------------------------------
 As I have created three threads and one thread print three numbers with starting 1 and ending 3 , thus will have three sets of
MyThread count=1
MyThread count=2
MyThread count=3

as theses are threads, there output may vary. Thread executes asynchronously. that is threads context switch with each other , in simple the execution has no real execution order.  Or in other way one thread need not to wait until the finish of other thread - that is the basic need of the thread.

So if we assume all three threads execute successfully, then we need to have 3 occurrences of
MyThread count=1
MyThread count=2
MyThread count=3

where    MyThread count=1, MyThread count=2 ,MyThread count=3 may print in different oder each time of Compare  main method executes.

For better understand, we can modify our MyThread run() method to print the name of the thread execution. So modification will be as follows.

-----------------------------------------------------------------------------------------------------------
public class MyThread extends Thread {

int count = 0;

public MyThread(String name) {
super(name);
}

@Override
public void run() {
for (int i = 0; i < 3; i++) {
count++;
System.out.println("MyThread "+Thread.currentThread().getName()+ " count="+count);
}
}
}

-----------------------------------------------------------------------------------------------------------


Output as follows. Note I have given names to threads as t1, t2, t3
You can observe that execution order differ from thread start order.

-----------------------------------------------------------------------------------------------------------
MyThread t2 count=1
MyThread t2 count=2
MyThread t2 count=3
MyThread t3 count=1
MyThread t3 count=2
MyThread t3 count=3
MyThread t1 count=1
MyThread t1 count=2
MyThread t1 count=3

-----------------------------------------------------------------------------------------------------------
If we get another output, it will be totally different.
-----------------------------------------------------------------------------------------------------------
MyThread t1 count=1
MyThread t3 count=1
MyThread t2 count=1
MyThread t2 count=2
MyThread t2 count=3
MyThread t1 count=2
MyThread t1 count=3
MyThread t3 count=2
MyThread t3 count=3
-----------------------------------------------------------------------------------------------------------

I Believe this would give you a clear picture of thread execution at glance, and let's stick to our discussion over creating Thread with extending Thread class Vs Implementation of Runnable.

So we have implemented thread simply with extending a thread class and our work has been implemented inside run() method.
That's it. very simple.
So what's the issue ????
Can you see something with MyThread class ??
it has already one extends, Thread class -- We cannot extends another class
That's a problem we have with Thread extends..

So how to get over with.
Java has given contract , Runnable interface with only run() method
Second way of creating a thread.

Question: Why we need to create a thread ???
Answer :  cause we need to do some work in asynchronously ..

OK.override the logic, work in run() method

Question: can we take the run() outside Thread class , so we can extends our thread "in the case MyThread"  with specific class and do the thread work separately.
Answer :  That's where Runnable  comes.

So let's implement same logic using Runnable

-----------------------------------------------------------------------------------------------------------

public class MyRunnable implements Runnable {

int count = 0;

public void run() {
for (int i = 0; i < 3; i++) {
count++;
System.out.println("MyRunnable " + Thread.currentThread().getName()+ " count=" + count);
}

}
}

-----------------------------------------------------------------------------------------------------------

So we have run() method override

Question: How we are going to run this thread. MyRunnable  class does not have any thread functionality. start() method



Answer : Java has given you way
Question: How ???
Answer : we create thread with extends Thread class. it has all functionality of thread implemented inside of it. Why not reuse Thread class
Question: Great   .... How to reuse it.
Answer : Thread class has constructor to accept Runnable instance
Question: So we need to create instance of the Runnable and create Thread instance using Thread class
Answer : Yes
Question : We are creating two instances ??
Answer : Yes..

That's how we reuse the functionality.

Question : I don't like creating two instances for create one thread object. Isn't it taking more memory and space ?? I prefer extends Thread class.. So I can straight away start() thread with creating instance.

Answer : We have pros and cons in both ways. Don't be so lazy. Runnable is a better implementation over extends Thread. we can keep thread logic separately and also we can extends another class. Don't you remember the problem we had over extends with Thread where we cannot extends only one class.

Question :Ok. Let's agree Runnable is better .
Answer  : You will see more magic in future.

Below Is the execution of Runnable , corresponding to output "MyThread"

main method

----------------------------------------------------------------------------------------------------------------

public class Compare {

public static void main(String[] args) {
MyRunnable myRunnable1 = new MyRunnable();
MyRunnable myRunnable2 = new MyRunnable();
MyRunnable myRunnable3 = new MyRunnable();
Thread r1 = new Thread(myRunnable1, "r1");
Thread r2 = new Thread(myRunnable2, "r2");
Thread r3 = new Thread(myRunnable3, "r3");
r1.start();
r2.start();
r3.start();
}
}

----------------------------------------------------------------------------------------------------------------

Out as below

----------------------------------------------------------------------------------------------------------------
MyRunnable r1 count=1
MyRunnable r1 count=2
MyRunnable r1 count=3
MyRunnable r2 count=1
MyRunnable r2 count=2
MyRunnable r2 count=3
MyRunnable r3 count=1
MyRunnable r3 count=2
MyRunnable r3 count=3
----------------------------------------------------------------------------------------------------------------

So same thing is done using Runnable. But we need to write some additional lines to create instances of Runnable for each thread.

                MyRunnable myRunnable1 = new MyRunnable();
MyRunnable myRunnable2 = new MyRunnable();
MyRunnable myRunnable3 = new MyRunnable();

You can simply give the created object as reference as below if needed. Simple java programming way of writing..

-------------------------------------------------------------------------------------------------------------------
public class Compare {

public static void main(String[] args) {

Thread r1 = new Thread(new MyRunnable(), "r1");
Thread r2 = new Thread(new MyRunnable(), "r2");
Thread r3 = new Thread(new MyRunnable(), "r3");
r1.start();
r2.start();
r3.start();
}
}

-------------------------------------------------------------------------------------------------------------------

It will produce same output
-------------------------------------------------------------------------------------------------------------------
MyRunnable r2 count=1
MyRunnable r2 count=2
MyRunnable r2 count=3
MyRunnable r1 count=1
MyRunnable r1 count=2
MyRunnable r1 count=3
MyRunnable r3 count=1
MyRunnable r3 count=2
MyRunnable r3 count=3

-------------------------------------------------------------------------------------------------------------------


So you don't have to worry about additional java code line writing.

So what's the other big deal with Runnable.???

With Runnable You can share the Runnable objet with threads. There by , we can pass process to another thread. Next thread will take upon from previous thread.

May be little confusing. Let's look at with the example.

Here we have created only once instance of Runnable and we have shared with three threads insteads.
Note : Shared 

New main method will be looks like this.
we have only one reference "myRunnable" and it is shared with all three threads.
-------------------------------------------------------------------------------------------------------------------
public class Compare {

public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();

Thread r1 = new Thread(myRunnable, "r1");
Thread r2 = new Thread(myRunnable, "r2");
Thread r3 = new Thread(myRunnable, "r3");
r1.start();
r2.start();
r3.start();
}
}


-------------------------------------------------------------------------------------------------------------------

Output will be as follows.
-------------------------------------------------------------------------------------------------------------------
MyRunnable r1 count=1
MyRunnable r1 count=2
MyRunnable r1 count=3
MyRunnable r2 count=4
MyRunnable r2 count=5
MyRunnable r2 count=6
MyRunnable r3 count=7
MyRunnable r3 count=8
MyRunnable r3 count=9
-------------------------------------------------------------------------------------------------------------------


See the output. Now the count is incremented by each time a thread executes.
How this happens.
we have created one Runnable instance/Object. "myRunnable", It is shared with all three threads.
when object is shared its property " count " is shared between threads, thus increment each time run()  method executes.

So as a brief following will be the outcomes we must remember when considering Extends Thread over Implment Runnable.


  1.  Java doesn't support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance and can not extend or inherit another class in Java.
  2. In Object oriented programming extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread than use Runnable interface instead.
  3. Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.
  4. Separating task as Runnable means we can reuse the task and also has liberty to execute it from different means. since you can not restart a Thread once it completes. again Runnable vs Thread for task, Runnable is winner. Reusability and Seperation.
  5. Java designer recognizes this and that's why Executors accept Runnable as Task and they have worker thread which executes those task.
  6. Inheriting all Thread methods are additional overhead just for representing a Task which can can be done easily with Runnable.
This is not the end. Java concurrency is a huge topic and let's go through one step at a time.
We have issues with the Thread and implementation of run() method, what to do if exception happens... how to handle those exceptions... can we return a value...

So next we look at Callable interface , which as some enhance functionality over Runnable.
Callable let's you return from run() method and handle exceptions. Java has change the name to call() - fair enough, that makes a difference and reduce the ambiguity also.

For Quick reviews on states, Threads has 4 different main states. New, Runnable, Running, Dead.
Runnable can be interchange with Running state and
Running state may go to Waiting/Blocked/(Sleep)
New - newly created thread is in this state.
Runnable -  once start() method called thread will be in Runnable state
Running - Runnable state will be picked and start executing , state will be Running - where thread actually does it work
Dead - once thread work finish, goes to dead state
Waiting/Blocked(Sleep) -  calling sleep, or with some interruption thread will be in Waiting/Blocked state. Once it come out from Waiting or Blocking thread will be in Runnable state.

Note: Thread class has yield() method. This will put Running thread back into Runnable state.
This it is said to be giving fair chance to all threads in the same priority as Yield() thread.
But as sleep(), it is also not guaranteed, same yield() thread may come back to Running straight after Runnable - thus not making fair chance to other threads in same priority.

Although we give the sleep time in millisecond, ex:500 mills , it is not guaranteed that it will be sleep for 500 mills . it can be start Running before after 500 mills.


One important method to remember is join(), where tells JVM to finish join thread before current thread.




Monday, February 16, 2015

Error in Iterrating over Entryset in Map

I just wrote a simple method to print the values of a given Map.
I gave the Map as a parameter for print Method and printing logic was implemented inside method.

But when i tried to iterate using simple "for loop" as below

--------------------------------------------------------------------------------------------------------

public static void printMapWithEntrySet(Map nameCount) {
for (Entry entry : nameCount.entrySet()) {
String key = entry.getKey().toString();

Integer value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}
}

---------------------------------------------------------------------------------------------------------

there was a Type mismatch error
( "Type mismatch: cannot convert from element type Object to Map.Entry") 
showing in the highlighted line.

for (Entry entry : nameCount.entrySet()) {

I found the reason, it was very simple mistake. error is in the parameter.
I have not included type in Map definition the parameter.
It should be

Map nameCount

So the correct formation of the method would be

----------------------------------------------------------------------------------------------------------

public static void printMapWithEntrySet(Map nameCount) {
for (Entry entry : nameCount.entrySet()) {
String key = entry.getKey().toString();

Integer value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}
}

----------------------------------------------------------------------------------------------------------

Because of that, Entry set object cannot cast the value for Entry and it comes as Object as stated below

----------------------------------------------------------------------------------------------------------

public static void printMapWithEntrySet(Map nameCount) {
for (Object entry : nameCount.entrySet()) {

}
}
----------------------------------------------------------------------------------------------------------


Without  the type definition of the Map , that is "" in  the parameter you can still implement the printing all values in a Map with using iterator.
So the code will looks like below.

----------------------------------------------------------------------------------------------------------
public static void printMap(Map nameCount) {

Iterator> it = nameCount.entrySet().iterator();
while (it.hasNext()) {
Entry pairs = (Entry) it.next();
System.out.println("key, " + pairs.getKey() + " value "
+ pairs.getValue());
}

}

----------------------------------------------------------------------------------------------------------

Here we have to use an Iterator. That is an additional burden.