hibernate的CRUD操作

╰+攻爆jí腚メ 2022-07-24 06:10 293阅读 0赞
  1. package dao;
  2. import entity.Address;
  3. import entity.Students;
  4. import org.hibernate.Session;
  5. import org.hibernate.SessionFactory;
  6. import org.hibernate.Transaction;
  7. import org.hibernate.cfg.Configuration;
  8. import org.hibernate.service.ServiceRegistry;
  9. import org.hibernate.service.ServiceRegistryBuilder;
  10. import java.util.Date;
  11. /**
  12. * Created by raid on 2016/5/14.
  13. */
  14. public class StudentsLogic {
  15. private SessionFactory sessionFactory;
  16. private Session session;
  17. private Transaction transaction;
  18. public void init() {
  19. //创建配置对象,获取hibernate.cfg.xml配置文件的信息
  20. Configuration config = new Configuration().configure();
  21. //创建服务创建对象,创建和销毁都相当耗费资源,通常一个系统内一个数据库只创建一个
  22. ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
  23. //创建会话工厂对象,类似于JDBC的Connection
  24. sessionFactory = config.buildSessionFactory(serviceRegistry);
  25. //创建会话对象的两种方式:
  26. //1.openSession
  27. // session = sessionFactory.openSession();
  28. //2.getCurrentSession,需要在配置文档中配置current session=thread
  29. /**
  30. * 如果获取session的方法是openSession(),关闭session的时候必须是session.close(),
  31. * 如果session获取通过getCurrentSession()获得的Session提交时自动关闭,其不用在session.close(),
  32. * 如果在调用session.close().其相当于session关闭两次 所以会出现Session was already closed异常
  33. */
  34. session = sessionFactory.getCurrentSession();
  35. //开启事务
  36. transaction = session.beginTransaction();
  37. }
  38. /**
  39. * 增加记录
  40. */
  41. public void add() {
  42. Students s = new Students("小小黑", "男", new Date(), "广东");
  43. Address ad = new Address("524394", "18826252094", "湛江");
  44. s.setAd(ad);
  45. //保存对象进入数据库
  46. session.save(s);
  47. }
  48. /**
  49. * get和load的区别:
  50. * 1.在不考虑缓存的情况下,get方法会在调用之后立即向数据库发出sql语句,返回持久化对象
  51. * load方法会在调用后返回一个代理对象
  52. * 该代理对象只保存了实体对象的id,直到使用对象的非主键属性时才会发出sql语句
  53. * 2.查询数据库中不存在的数据时,get方法返回null,load方法抛出异常
  54. */
  55. /**
  56. * 查询
  57. */
  58. public void select() {
  59. Students s = (Students) session.get(Students.class, 1);
  60. System.out.println(s);
  61. }
  62. /**
  63. * 查询
  64. */
  65. public void load() {
  66. Students s = (Students) session.load(Students.class, 1);
  67. System.out.println(s);
  68. }
  69. /**
  70. * 修改
  71. */
  72. public void update() {
  73. Students s = (Students) session.load(Students.class, 1);
  74. s.setSname("修改后的小小黑");
  75. session.update(s);
  76. }
  77. /**
  78. * 删除
  79. */
  80. public void delete() {
  81. Students s = (Students) session.get(Students.class, 2);
  82. session.delete(s);
  83. }
  84. public void destroy() {
  85. transaction.commit(); //提交事务
  86. // session.close(); //关闭会话
  87. sessionFactory.close(); //关闭会话工厂
  88. }
  89. }

发表评论

表情:
评论列表 (有 0 条评论,293人围观)

还没有评论,来说两句吧...

相关阅读