Q. What are the states of object in hibernate?
Update later
Types of Object state in hibernate –
- Transient
- Persistent
- Detached
Suppose we have one entity Book.java.
package simpleentity;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table(name = "book")
public class Book implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "book_id")
private int bookId;
@Column(name = "book_name")
private String bookName;
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
}
We also have hibernate.cfg.xml.
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver </property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property> <property name="connection.username">SYSTEM</property> <property name="connection.password">oracle</property> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">create</property> <mapping class="simpleentity.Book" /> </session-factory> </hibernate-configuration>
We have main class. ObjectStateExample.java
package onetoonetechhelpzones;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
public class ObjectStateExample {
public static void main(String[] args) {
SessionFactory factory = null;
Session session = null;
Configuration configuration = new Configuration().configure();
try {
factory = configuration.buildSessionFactory();
session = factory.openSession();
Transaction tx = session.beginTransaction();
Book b = new Book();
b.setBookName("book name 1");
session.save(b);
tx.commit();
System.out.println("transaction completed ");
} catch (Exception e) {
System.out.println(e);
} finally {
session.close();
factory.close();
}
}
}