org.hibernate.TransientObjectException:

Basically This exception occurs when we use Relationships(OneToOne,OneToMany,ManyToMany) between the Two Objects and not provide the cascade  types.

So if you get the following exception add

@ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY) etc...

Exception in thread “main” org.hibernate.TransientObjectException: object references an unsaved transient instance – save the transient instance before flushing: org.shashank.Users (for Ex:)
at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:243)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:456)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:121)
at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:815)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1203)
at org.hibernate.action.CollectionRecreateAction.execute(CollectionRecreateAction.java:58)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:188)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)

 

Hibernate Mismatch Probelms

  1. problem of Granularity
  2. problem of subTypes
  3. problem of Identity

 

     Problem of Granularity

In Java (Domain Model) we can define our custom data Types(User Defined Data Types) but in Database side (Data Model) we can’t   define our custom Data Types. This is called Problem of Granularity.

 

     Problem of Sub Types

In Java (Domain Model) we can define Parent and its child classes, where as in Data Model we don’t have a concept of  Table          Inheritance.

 

 

 

 

Hibernate granualirity example (Value Type)


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.sparity</groupId>
  <artifactId>HibernateXML</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>HibernateXML</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java-version>1.6</java-version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>3.6.0.Final</version>
		</dependency>

		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.18</version>
		</dependency>

		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.11.0.GA</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.5</version>
		</dependency>

		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
  </dependencies>

  <build>
  	<plugins>
  		<plugin>
  			<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>${java-version}</source>
					<target>${java-version}</target>
				</configuration>

  		</plugin>
  	</plugins>
  </build>
</project>

hiberante-cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>
 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
 <property name="connection.url">jdbc:mysql://localhost:3306/HibernateSave</property>
 <property name="connection.username">root</property>
 <property name="connection.password">sparity123</property>

<property name="hibernate.show_sql">true</property>
 <property name="hibernate.format_sql">true</property>
 <property name="hibernate.use_sql_comments">true</property>
 <property name="hibernate.connection.pool_size">10</property>
 <property name="hibernate.transaction.factory_class">
 org.hibernate.transaction.JDBCTransactionFactory</property>
 <!-- <property name="hibernate.hbm2ddl.auto">create</property> -->

 <!-- SQL dialect -->
 <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

 <mapping resource="com/sparity/hibernatexml/User.hbm.xml"/>

</session-factory>
</hibernate-configuration>

log4j.properties


# This is a testing confguration property file for the logging package.
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG,stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %-5p %c - %m%n

User.java


import java.io.Serializable;

public class User implements Serializable {
 private static final long serialVersionUID = -1498501116840102526L;

public User() {
 }

private Integer id;
 private String userName;
 private String name;
 private Address billingAddress;
 private Address homeAddress;

public Integer getId() {
 return id;
 }

public void setId(Integer id) {
 this.id = id;
 }

public String getUserName() {
 return userName;
 }

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

public String getName() {
 return name;
 }

public void setName(String name) {
 this.name = name;
 }

public Address getBillingAddress() {
 return billingAddress;
 }

public void setBillingAddress(Address billingAddress) {
 this.billingAddress = billingAddress;
 }

public Address getHomeAddress() {
 return homeAddress;
 }

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

}

Address.java


public class Address{

 private static final long serialVersionUID = 1385516332953914071L;
 private String street;
 private String city;
 private String zipCode;

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 getZipCode() {
 return zipCode;
 }

public void setZipCode(String zipCode) {
 this.zipCode = zipCode;
 }

}

User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

 <class name="com.sparity.hibernatexml.User" table="user">

 <id name="id" type="integer">
 <column name="id" />
 <generator class="identity" />
 </id>

 <property name="userName" type="string">
 <column name="user_name"></column>
 </property>

 <property name="name" type="java.lang.String">
 <column name="name" />
 </property>

 <component name="billingAddress" class="com.sparity.hibernatexml.Address">
 <property name="street" column="billing_street"/>
 <property name="city" column="billing_city"/>
 <property name="zipCode" column="billing_zipcode"/>
 </component>

 <component name="homeAddress" class="com.sparity.hibernatexml.Address">
 <property name="street" column="home_street"/>
 <property name="city" column="home_city"/>
 <property name="zipCode" column="home_zipcode"/>
 </component>

 </class>
</hibernate-mapping>

HibernateUtil.java

public class HibernateUtil {

 private static final Logger logger = Logger.getLogger(HibernateUtil.class);

 private static final SessionFactory sessionFactoryInstance = buildSessionFactory();

 private static SessionFactory buildSessionFactory(){
 SessionFactory sfc = null;
 try {
 Configuration cfg = new Configuration();
 cfg.configure("hibernate-config.xml");
 sfc = cfg.buildSessionFactory();
 } catch (HibernateException e) {
 logger.error("Error creating session factory");
 e.printStackTrace();
 }

 return sfc;
 }

 public static SessionFactory getSessionFactory(){
 return sessionFactoryInstance;
 }

}

App.java



 public static void main( String[] args )
 {

 // creating billing address
 Address billingAddress = new Address();
 billingAddress.setStreet("BapuNagar");
 billingAddress.setCity("Hyderabad");
 billingAddress.setZipCode("789456123");

 //creating home address

 Address homeAddress = new Address();
 homeAddress.setStreet("amruthacolony");
 homeAddress.setCity("Hyderabad");
 homeAddress.setZipCode("50000213");

 User newUser = new User();

 newUser.setUserName("Srinivas");
 newUser.setName("JanakiSrinivas");
 newUser.setBillingAddress(billingAddress);
 newUser.setHomeAddress(homeAddress);

 // to save object in database

 /* Configuration cfg = new Configuration();
 cfg.configure("hibernate-config.xml");*/
 SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
 Session session = sessionFactory.openSession();
 Transaction tx = session.beginTransaction();
 session.save(newUser);
 session.flush();
 tx.commit();
 session.close();

 }
}