// fruit.setComments("hello"); // fruit.setPrice(100);
FruitManager fm=new FruitManager(); fm.insert(fruit); } public static void main(String[] args) { // TODO 自动生成方法存根 Test t=new Test(); t.test1(); }
}
hibernate API(一): Configuration: 读取配置文件信息用来初始化的 SessionFactory: 重量级对象,特点:消耗资源大,线程是安全,所以可以被共享 上面两个对象只实例化一个就行了,都是用于初始化的 Session: 线程是不安全的,所以要避免多个线程共享它,是轻量级的对象,使用后关闭
Session对象的状态: 顺态: 还没有被持久化,也就是说数据库中没有该对象的记录,并且Session中的缓冲区里没有这个对象的引用 持久态: 在数据库中有该对象的记录,并且在session中的缓冲区里有这个对象的引用,和顺态正好相反 游离态: 在数据库中有记录,但是不在session的缓冲区里
对象状态的转换: 做一个工具类,将hibernate中重复的代码包装起来: package Yuchen.fristHbn.util; //生产session对象的工具类 import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;
public class HbnUtil { private static SessionFactory sf; static{ sf=new Configuration().configure().buildSessionFactory(); }
public static Session getSession(){ return sf.openSession(); } }
完善FruitManager类: package Yuchen.fristHbn.business.Biz; //业务逻辑类:负责增删改查通过使用hibernate API进行 import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration;
import Yuchen.fristHbn.business.entity.Fruit; import Yuchen.fristHbn.util.HbnUtil;
public class FruitManager { public Integer insert(Fruit fruit){ Session session=HbnUtil.getSession();//通过工具更方便了 Integer id=null; // Configuration config=new Configuration(); // config.configure();//读配置文件 // SessionFactory sf=config.buildSessionFactory();//得到工厂 // Session session=sf.openSession();//得到session Transaction tt=session.beginTransaction();//检查事务开启 id=(Integer)session.save(fruit);//存储insert tt.commit();//提交 session.close();//关闭资源 return id; }
public Fruit selectId(Integer id){ Session session=HbnUtil.getSession(); Transaction t=session.beginTransaction(); Fruit fruit=(Fruit)session.get(Fruit.class, id); t.commit(); session.close(); return fruit; }
public void remove(Fruit fruit){ Session session=HbnUtil.getSession(); Transaction t=session.beginTransaction(); session.delete(fruit); t.commit(); session.close(); } }
测试对象状态的转换: /** * 知识点: * hibernate基础:练习语法部分API和简单的映射关系 * 程序目标: * 使用hibernate方法将对象进行持久化
上一篇:Hibernate中的Session什么时候关闭?
下一篇:struts+hibernate如何整合在一起?
|