Hibernate的基本CRUD

港控/mmm° 2022-06-16 04:26 406阅读 0赞
  1. package cn.itcast.b_dao;
  2. import java.util.List;
  3. import org.hibernate.Criteria;
  4. import org.hibernate.Session;
  5. import org.hibernate.Transaction;
  6. import cn.itcast.a_helloworld.User;
  7. public class UserDao {
  8. /**
  9. * 保存
  10. *
  11. * @param user
  12. * 用户
  13. */
  14. public void save(User user) {
  15. Session session = HibernateUtils.opensession();
  16. Transaction tx = null;
  17. try {
  18. tx = session.beginTransaction();// 开始事务
  19. // 保存
  20. session.save(user);
  21. tx.commit();// 提交事务
  22. } catch (RuntimeException e) {
  23. tx.rollback();// 回滚事务
  24. throw e;
  25. } finally {
  26. session.close();// 释放资源
  27. }
  28. }
  29. /**
  30. * 更新
  31. *
  32. * @param user
  33. * 用户
  34. */
  35. public void update(User user) {
  36. Session session = HibernateUtils.opensession();
  37. Transaction tx = null;
  38. try {
  39. tx = session.beginTransaction();
  40. // 操作
  41. session.update(user);
  42. tx.commit();// 提交事务
  43. } catch (RuntimeException e) {
  44. tx.rollback();// 回棍事务
  45. throw e;
  46. } finally {
  47. session.close();// 释放资源
  48. }
  49. }
  50. /**
  51. * 删除
  52. *
  53. * @param id
  54. * 根据id删除数据
  55. */
  56. public void delete(Integer id) {
  57. Session session = HibernateUtils.opensession();
  58. Transaction tx = null;
  59. try {
  60. tx = session.beginTransaction();
  61. // 操作
  62. Object user = session.get(User.class, id);// 要先获取到这个对象
  63. session.delete(user);// 删除的是实体对象
  64. tx.commit();// 提交事务
  65. } catch (RuntimeException e) {
  66. tx.rollback();// 回滚事务
  67. throw e;
  68. } finally {
  69. session.close();// 释放资源
  70. }
  71. }
  72. /**
  73. * 根据id查询一个User数据
  74. *
  75. * @param id
  76. * 根据id查询数据
  77. * @return 返回一条User数据
  78. */
  79. public User getById(Integer id) {
  80. Session session = HibernateUtils.opensession();
  81. Transaction tx = null;
  82. try {
  83. tx = session.beginTransaction();// 打开事务
  84. // 操作
  85. User user = (User) session.get(User.class, id);
  86. tx.commit();// 提交事务
  87. return user;
  88. } catch (RuntimeException e) {
  89. tx.rollback();// 回滚事务
  90. throw e;
  91. } finally {
  92. session.close();// 释放资源;
  93. }
  94. }
  95. /**
  96. * 查询所有用户
  97. *
  98. * @return 返回所有用户
  99. */
  100. @SuppressWarnings("unchecked")
  101. public List<User> findAll() {
  102. Session session = HibernateUtils.opensession();
  103. Transaction tx = null;
  104. try {
  105. tx = session.beginTransaction();// 开始事务
  106. // 方式一: 使用HQL查询
  107. // List<User> list = session.createQuery(//
  108. // "FROM User WHERE id=5 order by id")//
  109. // .list();
  110. // 方式二:使用Criteria查询
  111. Criteria criteria = session.createCriteria(User.class);
  112. // criteria.add(Restrictions.eq("id", 5));
  113. // criteria.addOrder(Order.desc("id"));
  114. List<User> list = criteria.list();
  115. tx.commit();// 提交事务
  116. return list;
  117. } catch (RuntimeException e) {
  118. tx.rollback();
  119. // session.getTransaction().rollback();// 回滚事务
  120. throw e;
  121. } finally {
  122. session.close();// 释放资源
  123. }
  124. }
  125. /**
  126. * * 分页的查询数据列表
  127. *
  128. * @param firstResult
  129. * 从结果列表中那个索引开始取数据
  130. * @param maxResult
  131. * 最多取多少条数据
  132. * @return 一页的数据列表 + 总计录数
  133. */
  134. /**
  135. * @param firstResult
  136. * @param maxResult
  137. * @return
  138. */
  139. @SuppressWarnings("unchecked")
  140. public QueryResult findAll(Integer firstResult, Integer maxResult) {
  141. Session session = HibernateUtils.opensession();
  142. Transaction tx = null;
  143. try {
  144. tx = session.beginTransaction();// 开始事务
  145. // 查询一页的数据列表
  146. // 方式1
  147. // Query query = session.createQuery("FROM User");
  148. // query.setFirstResult(firstResult);
  149. // query.setMaxResults(maxResult);
  150. // List<User> list = query.list();// 操作
  151. // 方式2
  152. List<User> list = session.createQuery(//
  153. "FROM User")//
  154. .setFirstResult(firstResult)//
  155. .setMaxResults(maxResult)//
  156. .list();
  157. // 查询总记录数
  158. Long count = (Long) session.createQuery(//
  159. "SELECT COUNT(*) FROM User")//
  160. .uniqueResult();
  161. tx.commit();// 提交事务
  162. // 返回结果
  163. return new QueryResult(count.intValue(), list);
  164. } catch (RuntimeException e) {
  165. tx.rollback();// 回滚事务
  166. throw e;
  167. } finally {
  168. session.close();// 释放资源
  169. }
  170. }
  171. }
  172. package cn.itcast.b_dao;
  173. import org.hibernate.SessionFactory;
  174. import org.hibernate.cfg.Configuration;
  175. import org.hibernate.classic.Session;
  176. public class HibernateUtils {
  177. // SessionFactory全局只需要一个就行了
  178. private static SessionFactory sessionFactory;
  179. static {
  180. // Configuration cfg = new Configuration();
  181. // cfg.configure();// 读取默认配置文件(hibernate.cfg.xml)
  182. // // cfg.configure("hibernate.cfg.xml");//读取指定位置的配置文件
  183. // sessionFactory = cfg.buildSessionFactory();//生成会话工厂
  184. //初始化SessionFactory
  185. sessionFactory = new Configuration()//
  186. .configure()//
  187. .buildSessionFactory();
  188. }
  189. /**
  190. * 获取全局唯一的SessionFactory
  191. *
  192. * @return 返回SessionFactory
  193. */
  194. public static SessionFactory getSessionFactory() {
  195. return sessionFactory;
  196. }
  197. /**
  198. * 从全局唯一的SessionFactory中打开一个Session
  199. *
  200. * @return 返回Session
  201. */
  202. public static Session opensession() {
  203. return sessionFactory.openSession();
  204. }
  205. }
  206. package cn.itcast.b_dao;
  207. import java.util.List;
  208. /**
  209. * 查询结果分页
  210. *
  211. * @author 风清杨
  212. * @version V1.0
  213. */
  214. @SuppressWarnings("rawtypes")
  215. public class QueryResult {
  216. private int count;// 总记录数
  217. private List list;// 一页的数据
  218. public QueryResult(int count, List list) {
  219. this.count = count;
  220. this.list = list;
  221. }
  222. public int getCount() {
  223. return count;
  224. }
  225. public void setCount(int count) {
  226. this.count = count;
  227. }
  228. public List getList() {
  229. return list;
  230. }
  231. public void setList(List list) {
  232. this.list = list;
  233. }
  234. }

User.hbm.xml

  1. <?xml version="1.0"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5. <!-- 导入包 -->
  6. <hibernate-mapping package="cn.itcast.a_helloworld">
  7. <!-- 类名 -->
  8. <class name="User" table="t_user">
  9. <!-- id int类型 -->
  10. <id name="id" type="int" column="id">
  11. <!-- 自增长 -->
  12. <generator class="native"/>
  13. </id>
  14. <property name="name" type="string" column="name"/>
  15. </class>
  16. </hibernate-mapping>

Hibernate.cfg.xml

  1. <!DOCTYPE hibernate-configuration PUBLIC
  2. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  3. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  4. <hibernate-configuration>
  5. <session-factory name="foo">
  6. <!-- 配置数据库信息 -->
  7. <!-- 方言 -->
  8. <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  9. <!-- mysql连接配置 -->
  10. <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_20170423</property>
  11. <!-- 配置连接mysql驱动 -->
  12. <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  13. <!-- mysql用户名 -->
  14. <property name="connection.username">root</property>
  15. <!-- mysql密码 -->
  16. <property name="hibernate.connection.password">root</property>
  17. <!-- 其它配置 -->
  18. <!-- 显示生成的SQL语句 -->
  19. <property name="hibernate.show_sql">true</property>
  20. <!-- 格式化SQL语 -->
  21. <property name="hibernate.format_sql">false</property>
  22. <!-- create:先删除,再创建。 update:如果表不存在就创建,不一样就更新,一样就什么都不做。 create-dorp:初始化时创建表,SessionFactory执行close()时删除表。
  23. validate:验证表结构是否一致,如果不一致,就抛异常。 -->
  24. <property name="hbm2ddl.auto">update</property>
  25. <!-- 导入映射文件 -->
  26. <mapping resource="cn/itcast/c_hbm_property/User.hbm.xml" />
  27. </session-factory>
  28. </hibernate-configuration>

发表评论

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

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

相关阅读