标签:nal maven 通过 read cte user efault userinfo local
最近在学习Hibernate,貌似起步晚了些。以前都只是在用,没有进行系统地学习。刚刚开通了博客,想写一些学习笔记。如有错误之处,望列位指正,不甚感激。
USE DATABASE hibernatedb;--使用hibernatedb数据库
CREATE TABLE userinfo(
userId INT PRIMARY KEY AUTO_INCREMENT,
userName VARCHAR(20) NOT NULL,
userPassword VARCHAR(20) NOT NULL
);
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6 <session-factory> 7 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> 8 <property name="hibernate.connection.username">user1</property> 9 <property name="hibernate.connection.password">user1</property> 10 <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedb</property> 11 <!-- 配置数据库方言 --> 12 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 13 <property name="connection.pool_size">1</property> 14 <!-- 输出运行时生成的SQL语句 --> 15 <property name="show_sql">true</property> 16 <!-- 列出所有的映射文件 --> 17 <mapping resource="org/hibernate/entity/UserInfo.hbm.xml" /> 18 </session-factory> 19 </hibernate-configuration>
1 package org.hibernate.entity; 2 /** 3 * 4 * 功能:测试用用户类 5 * @author liaody 6 * @version 1.0 7 * @date 2017年3月5日 上午12:26:20 8 */ 9 public class UserInfo { 10 11 private int userId; 12 private String userName; 13 private String userPassword; 14 15 /** 16 * default constructor 17 */ 18 public UserInfo (){ 19 20 } 21 22 /** 23 * full constructor 24 * @param userId 25 * @param userName 26 * @param userPassword 27 */ 28 public UserInfo(int userId,String userName,String userPassword){ 29 this.userId = userId; 30 this.userName = userName; 31 this.userPassword = userPassword; 32 } 33 34 /** 35 * @return the userId 36 */ 37 public int getUserId() { 38 return this.userId; 39 } 40 41 /** 42 * @return the userName 43 */ 44 public String getUserName() { 45 return this.userName; 46 } 47 48 /** 49 * @return the userPassword 50 */ 51 public String getUserPassword() { 52 return this.userPassword; 53 } 54 55 /** 56 * @param userId the userId to set 57 */ 58 public void setUserId(int userId) { 59 this.userId = userId; 60 } 61 62 /** 63 * @param userName the userName to set 64 */ 65 public void setUserName(String userName) { 66 this.userName = userName; 67 } 68 69 /** 70 * @param userPassword the userPassword to set 71 */ 72 public void setUserPassword(String userPassword) { 73 this.userPassword = userPassword; 74 } 75 76 77 78 79 }
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 4 <hibernate-mapping> 5 <class name="org.hibernate.entity.UserInfo" table="USERINFO"> 6 <id name="userId" type="java.lang.Integer" column="userid"> 7 <generator class="increment" /> 8 </id> 9 <property name="userName" type="java.lang.String"> 10 <column name="userName" length="20"></column> 11 </property> 12 <property name="userPassword" type="java.lang.String"> 13 <column name="userPassword" length="20"></column> 14 </property> 15 </class> 16 </hibernate-mapping>
1 package org.hibernate.util; 2 3 import org.hibernate.*; 4 import org.hibernate.cfg.*; 5 6 public class HibernateUtil { 7 private static SessionFactory sessionFactory; 8 private static Configuration configuration = new Configuration(); 9 // 创建线程局部变量threadLocal,用来保存Hibernate的Session 10 private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); 11 // 使用静态代码块初始化Hibernate 12 static { 13 try { 14 Configuration cfg = new Configuration().configure(); // 读取配置文件hibernate.cfg.xml 15 sessionFactory = cfg.buildSessionFactory(); // 创建SessionFactory 16 } catch (Throwable ex) { 17 throw new ExceptionInInitializerError(ex); 18 } 19 } 20 21 // 获得SessionFactory实例 22 public static SessionFactory getSessionFactory() { 23 return sessionFactory; 24 } 25 26 // 获得ThreadLocal 对象管理的Session实例. 27 public static Session getSession() throws HibernateException { 28 Session session = (Session) threadLocal.get(); 29 if (session == null || !session.isOpen()) { 30 if (sessionFactory == null) { 31 32 rebuildSessionFactory(); 33 } 34 // 通过SessionFactory对象创建Session对象 35 session = (sessionFactory != null) ? sessionFactory.openSession() 36 : null; 37 // 将新打开的Session实例保存到线程局部变量threadLocal中 38 threadLocal.set(session); 39 } 40 return session; 41 } 42 43 // 关闭Session实例 44 public static void closeSession() throws HibernateException { 45 // 从线程局部变量threadLocal中获取之前存入的Session实例 46 Session session = (Session) threadLocal.get(); 47 threadLocal.set(null); 48 if (session != null) { 49 session.close(); 50 } 51 } 52 53 // 重建SessionFactory 54 public static void rebuildSessionFactory() { 55 try { 56 configuration.configure("/hibernate.cfg.xml"); // 读取配置文件hibernate.cfg.xml 57 sessionFactory = configuration.buildSessionFactory(); // 创建SessionFactory 58 } catch (Exception e) { 59 System.err.println("Error Creating SessionFactory "); 60 e.printStackTrace(); 61 } 62 } 63 64 // 关闭缓存和连接池 65 public static void shutdown() { 66 getSessionFactory().close(); 67 } 68 }
1 package org.hibernate.dao; 2 3 import org.hibernate.entity.UserInfo; 4 5 public interface UserInfoDao { 6 7 void save(UserInfo user); // 添加用户 8 9 UserInfo findById(int id); // 根据用户标识查找指定用户 10 11 void delete(UserInfo user); // 删除用户 12 13 void update(UserInfo user); // 修改用户信息 14 }
1 package org.hibernate.dao.impl; 2 3 import org.hibernate.Session; 4 import org.hibernate.Transaction; 5 import org.hibernate.dao.UserInfoDao; 6 import org.hibernate.entity.UserInfo; 7 import org.hibernate.util.HibernateUtil; 8 9 public class UserInfoDaoImpl implements UserInfoDao { 10 // 添加用户 11 public void save(UserInfo user) { 12 Session session = HibernateUtil.getSession(); // 生成Session实例 13 Transaction tx = session.beginTransaction(); // 创建Transaction实例 14 try { 15 session.save(user); // 使用Session的save方法将持久化对象保存到数据库 16 tx.commit(); // 提交事务 17 } catch (Exception e) { 18 e.printStackTrace(); 19 tx.rollback(); // 回滚事务 20 } finally { 21 HibernateUtil.closeSession(); // 关闭Session实例 22 } 23 } 24 25 // 根据用户标识查找指定用户 26 public UserInfo findById(int userId) { 27 UserInfo user = null; 28 Session session = HibernateUtil.getSession(); // 生成Session实例 29 Transaction tx = session.beginTransaction(); // 创建Transaction实例 30 try { 31 user = (UserInfo) session.get(UserInfo.class, userId); // 使用Session的get方法获取指定id的用户到内存中 32 tx.commit(); // 提交事务 33 } catch (Exception e) { 34 e.printStackTrace(); 35 tx.rollback(); // 回滚事务 36 } finally { 37 HibernateUtil.closeSession(); // 关闭Session实例 38 } 39 return user; 40 } 41 42 // 删除用户 43 public void delete(UserInfo user) { 44 Session session = HibernateUtil.getSession(); // 生成Session实例 45 Transaction tx = session.beginTransaction(); // 创建Transaction实例 46 try { 47 session.delete(user); // 使用Session的delete方法将持久化对象删除 48 tx.commit(); // 提交事务 49 } catch (Exception e) { 50 e.printStackTrace(); 51 tx.rollback(); // 回滚事务 52 } finally { 53 HibernateUtil.closeSession(); // 关闭Session实例 54 } 55 } 56 57 // 修改用户信息 58 public void update(UserInfo user) { 59 Session session = HibernateUtil.getSession(); // 生成Session实例 60 Transaction tx = session.beginTransaction(); // 创建Transaction实例 61 try { 62 session.update(user); // 使用Session的update方法更新持久化对象 63 tx.commit(); // 提交事务 64 } catch (Exception e) { 65 e.printStackTrace(); 66 tx.rollback(); // 回滚事务 67 } finally { 68 HibernateUtil.closeSession(); // 关闭Session实例 69 } 70 } 71 72 }
1 package org.hibernate.test; 2 3 import org.hibernate.dao.UserInfoDao; 4 import org.hibernate.dao.impl.UserInfoDaoImpl; 5 import org.hibernate.entity.UserInfo; 6 import org.junit.Before; 7 import org.junit.Test; 8 9 public class UserInfoTest { 10 11 @Before 12 public void setUp() throws Exception { 13 14 } 15 16 @Test 17 public void testSave() { 18 UserInfoDao userdao = new UserInfoDaoImpl(); 19 UserInfo user = new UserInfo(); // 创建UserInfo对象 20 // 设置UserInfo对象中的各个属性值 21 user.setUserName("liaody"); 22 user.setUserPassword("456"); 23 userdao.save(user); // 使用UserInfoDao的save方法将UserInfo对象存入数据库 24 25 } 26 }
这儿只是一个demo,为了能使用Hibernate进行增删改查,代码和结构之后会逐步完善。接下来将会对hibernate进行系统的学习。
标签:nal maven 通过 read cte user efault userinfo local
原文地址:http://www.cnblogs.com/yuanhaha/p/6503381.html