hibernate的CRUD操作 ╰+攻爆jí腚メ 2022-07-24 06:10 162阅读 0赞 package dao; import entity.Address; import entity.Students; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import java.util.Date; /** * Created by raid on 2016/5/14. */ public class StudentsLogic { private SessionFactory sessionFactory; private Session session; private Transaction transaction; public void init() { //创建配置对象,获取hibernate.cfg.xml配置文件的信息 Configuration config = new Configuration().configure(); //创建服务创建对象,创建和销毁都相当耗费资源,通常一个系统内一个数据库只创建一个 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //创建会话工厂对象,类似于JDBC的Connection sessionFactory = config.buildSessionFactory(serviceRegistry); //创建会话对象的两种方式: //1.openSession // session = sessionFactory.openSession(); //2.getCurrentSession,需要在配置文档中配置current session=thread /** * 如果获取session的方法是openSession(),关闭session的时候必须是session.close(), * 如果session获取通过getCurrentSession()获得的Session提交时自动关闭,其不用在session.close(), * 如果在调用session.close().其相当于session关闭两次 所以会出现Session was already closed异常 */ session = sessionFactory.getCurrentSession(); //开启事务 transaction = session.beginTransaction(); } /** * 增加记录 */ public void add() { Students s = new Students("小小黑", "男", new Date(), "广东"); Address ad = new Address("524394", "18826252094", "湛江"); s.setAd(ad); //保存对象进入数据库 session.save(s); } /** * get和load的区别: * 1.在不考虑缓存的情况下,get方法会在调用之后立即向数据库发出sql语句,返回持久化对象 * load方法会在调用后返回一个代理对象 * 该代理对象只保存了实体对象的id,直到使用对象的非主键属性时才会发出sql语句 * 2.查询数据库中不存在的数据时,get方法返回null,load方法抛出异常 */ /** * 查询 */ public void select() { Students s = (Students) session.get(Students.class, 1); System.out.println(s); } /** * 查询 */ public void load() { Students s = (Students) session.load(Students.class, 1); System.out.println(s); } /** * 修改 */ public void update() { Students s = (Students) session.load(Students.class, 1); s.setSname("修改后的小小黑"); session.update(s); } /** * 删除 */ public void delete() { Students s = (Students) session.get(Students.class, 2); session.delete(s); } public void destroy() { transaction.commit(); //提交事务 // session.close(); //关闭会话 sessionFactory.close(); //关闭会话工厂 } }
还没有评论,来说两句吧...