本篇博客是初学hibernate时笔记总结,主要总结hibernate的三种状态和hibernate的CRUD操作。
具体的分析推荐一篇博客写的很详细,也很容易理解,
Hibernate三种状态的详解,
2.1 Bean对象
package com.qian.domain;
import java.util.Date;
public class User2 {
private String user2Id;
private String user2Name;
private Date user2CreateDate;
public String getUser2Id() {
return user2Id;
}
public void setUser2Id(String user2Id) {
this.user2Id = user2Id;
}
public String getUser2Name() {
return user2Name;
}
public void setUser2Name(String user2Name) {
this.user2Name = user2Name;
}
public Date getUser2CreateDate() {
return user2CreateDate;
}
public void setUser2CreateDate(Date user2CreateDate) {
this.user2CreateDate = user2CreateDate;
}
}
User2.hbm.xml文件
<hibernate-mapping package="com.qian.domain">
<class name="User2" table="t_User2">
<id name="user2Id" column="User2_ID">
<generator class="uuid"/>
id>
<property name="user2Name"/>
<property name="user2CreateDate"/>
class>
hibernate-mapping>
hibernate.cfg.xml文件
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.OracleDriverproperty>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:ORCLproperty>
<property name="connection.username">scottproperty>
<property name="connection.password">qianproperty>
<property name="connection.pool_size">1property>
<property name="dialect">org.hibernate.dialect.OracleDialectproperty>
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProviderproperty>
<property name="show_sql">trueproperty>
<mapping resource="com/qian/domain/User.hbm.xml"/>
<mapping resource="com/qian/domain/User2.hbm.xml"/>
session-factory>
hibernate-configuration>
hbm2ddl类
package com.qian.envir;
import java.util.EnumSet;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
/**
* http://blog.csdn.net/qinshijangshan/article/details/53314230
* http://bbs.csdn.net/topics/391942178?page=1
* 参考网页来分析所在版本的不同SchemaExport变化的集中方式,
* create
* @author Administrator
*
*/
public class ExoprotDB {
public static void main(String[] args) {
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
MetadataImplementor metadataImplementor = (MetadataImplementor) new MetadataSources(serviceRegistry)
.buildMetadata();
SchemaExport export = new SchemaExport();
export.create(EnumSet.of(TargetType.DATABASE), metadataImplementor);
}
}
HibernateUtil类
package com.qian.envir;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private static SessionFactory sessionFactory;
//生成sessionFactory;
static{
final StandardServiceRegistry standardServiceRegistry = new
StandardServiceRegistryBuilder().configure().build();
try{
sessionFactory = new MetadataSources(standardServiceRegistry)
.buildMetadata().buildSessionFactory();
}catch(Exception e){
StandardServiceRegistryBuilder.destroy(standardServiceRegistry);
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
public static Session getSession(){
return sessionFactory.openSession();
}
public static void freeSession(Session session){
if(session!=null){
if(session.isOpen()){
session.close();
}
}
}
}
CRUD测试类代码
package test.qian;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.qian.domain.User2;
import com.qian.envir.HibernateUtil;
import junit.framework.TestCase;
public class CRUDTest extends TestCase {
public void testCreate(){
//step one:读取hibernate.cfg.xml文件拿到sessionFactory
//由于sessionFactory相当于DB的镜像,并且创建很花时间,我们可以写一个工具类只创建一次;
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = null;
Transaction transaction = null;
try{
//stpe two: 通过sessionFactroy拿到session
session = sessionFactory.openSession();
//step three: 开启事务-->提交是否-->捕获异常事务回滚
transaction = session.getTransaction();
transaction.begin();
//step four: 写添加用户的测试代码
User2 user2 = new User2();
user2.setUser2Id("u2id");
user2.setUser2Name("userName");
user2.setUser2CreateDate(new Date());
//step five: 保存到数据库中
session.save(user2);
transaction.commit();
}catch(Exception e){
transaction.rollback();
e.printStackTrace();
}finally{
//step six: 无论成功与否释放session
HibernateUtil.freeSession(session);
}
}
public void testReadByGet(){
//step one:
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session =null;
Transaction transaction = null;
try{
//step two:
session = sessionFactory.openSession();
//step three:
transaction = session.getTransaction();
transaction.begin();
//step four:
//get方法的第一个参数为 Class对象, 第二个参数为Serializable类型(key),也就是根据id查值
//get方法获取的对象是持久化对象,如果没有找到则返回null,不会报错。
//发出get查询,它就会马上去数据库中查找,因为是持久化对象,如果我们改变了对象的属性,在最后
//的commit是,及时没有update,Hibernate也会对照数据库中的对象和内存中的对象,对数据进行更改;
User2 user2 = session.get(User2.class, "402880da5e50fc2d015e50fc30b10000");
if(user2!=null)
System.out.println(user2.getUser2Name()+" : "+user2.getUser2CreateDate());
//user2.setUser2Name("如果这里对属性操作,会同步到数据库");
transaction.commit();
}catch(Exception e){
transaction.rollback();
e.printStackTrace();
}finally{
HibernateUtil.freeSession(session);
}
}
public void testReadByLoad(){
//step one:
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session =null;
Transaction transaction = null;
try{
//step two:
session = sessionFactory.openSession();
//step three:
transaction = session.getTransaction();
transaction.begin();
//step four:
//load方法的第一个参数为 Class对象, 第二个参数为Serializable类型(key),也就是根据id查值
//load方法获取的对象是持久化对象,如果没有找到则抛出对象没找到异常。
//发出load查询,它不会马上去数据库中查找,而是创建一个User2的代理对象,当真正用的时候才会
//向数据库发出查询语句。也就是load使用CGLIB的动态代理来实现懒加载的。
//的commit是,及时没有update,Hibernate也会对照数据库中的对象和内存中的对象,对数据进行更改;
User2 user2 = session.load(User2.class, "402880da5e50fc2d015e50fc30b10000");
System.out.println(user2.getUser2Name()+" : "+user2.getUser2CreateDate());
user2.setUser2Name("如果持久化对象 对属性操作,会同步到数据库");
transaction.commit();
}catch(Exception e){
transaction.rollback();
e.printStackTrace();
}finally{
HibernateUtil.freeSession(session);
}
}
public void testUpdate(){
//step one:
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session =null;
Transaction transaction = null;
try{
//step two:
session = sessionFactory.openSession();
//step three:
transaction = session.getTransaction();
transaction.begin();
//step four:
User2 user2 = session.load(User2.class, "402880da5e50fc2d015e50fc30b10000");
user2.setUser2Name("zhangSan");
//step five:
session.update(user2);
transaction.commit();
}catch(Exception e){
transaction.rollback();
e.printStackTrace();
}finally{
HibernateUtil.freeSession(session);
}
}
public void testDelete(){
//step one:
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session =null;
Transaction transaction = null;
try{
//step two:
session = sessionFactory.openSession();
//step three:
transaction = session.getTransaction();
transaction.begin();
//step four:
User2 user2 = session.load(User2.class, "402880da5e50fc2d015e50fc30b10000");
session.delete(user2);
System.out.println("delete successfully");
transaction.commit();
}catch(Exception e){
transaction.rollback();
e.printStackTrace();
}finally{
HibernateUtil.freeSession(session);
}
}
}