Hibernate- CURD Operations

Hibernate CURD Operations

Now we will see how to insert, delete, update & select data from/into database using hibernate.

Session class will have the following methods to perform CURD Operations

Session class methods

Select

Object	get(Class , Serializable id)
Object	load(Class, Serializable id)

Insert

Serializable	save(Object object) 
void persist(Object object) 
void saveOrUpdate(Object object)

Update

Object	merge(Object object) 
void	update(Object object)

Delete

void	delete(Object object)

Clear

void	evict(Object object) :   Remove this instance from the session cache.
void	clear()   :   Completely clear the session.

Other

boolean	isDirty() :   
--------------------------------------
Does this session contain any changes which must be 
synchronized with the database? 
In other words, would any DML operations be executed,
if we flushed this session?

void	refresh(Object object) 
---------------------------------------
Re-read the state of the given instance from the underlying database.


Below files are common to all CURD operation examples, follow the Steps

1. Choose Database Table

mysql> select * from employee;
+-----+--------+-------------+
| eid | name   | address     |
+-----+--------+-------------+
|   1 | Satya  | VIJYAYAWADA |
|   2 | Ravi   | HYDERABAD   |
|   3 | SURYA  | HYDERABAD   |
|   4 | RAMAN  | PUNE        |
|   5 | DILEEP | BANGLORE    |
|   6 | DILEEP | BANGLORE    |
+-----+--------+-------------+

2. POJO class(EmployeeBo.java)

package bo;
public class EmployeeBo {
	 private int eid;
	 private String name;
	 private String address;
 
//Setters& getters 
}

3. O/R Mapping XML(EmployeeBo.hbm.xml)

<hibernate-mapping>
	<class name="bo.EmployeeBo" table="employee">
 <id name="eid" column="eid">
 	<generator class="assigned" />
 </id>
 <property name="name" column="name" />
 <property name="address" column="address" />
	</class>
</hibernate-mapping>

4. Hibernate Configuration file

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration SYSTEM
"hibernate-configuration-3.0.dtd">

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

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>

<mapping resource="EmployeeBo.hbm.xml" />
</session-factory>
</hibernate-configuration>