`
sw1982
  • 浏览: 504119 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Hibernate笔记1

阅读更多

首先要感谢满江红社区:)给我们翻译了大量高质量的文档,我学习hibernate的文档资料主要来自他们的贡献。

对Hibernate概念模糊的一定要去看看 夏昕 写的《Hibernate 开发指南 》

 

一。Hibernate最小依赖包

手动添加每个项目的最小依赖包,并认识每个jar的大体作用是很有必要的:)

 

二、加载方式与核心类

1.加载Session

Session是持久层操作的基础,相当于JDBC中的 Connection。(注意Hibernate3中使用了与Hibernate2中不同的Session。老式的Session被迁移到org.hibernate.classic.Session)

 

Hibernate3以后应该使用如下的加载代码,可以获得绑定线程的Session变量。

  1.     public void getSession() {
  2.         try {
  3.             Configuration cfg = new Configuration().configure();
  4.             SessionFactory sf = cfg.buildSessionFactory();
  5.             session = sf.getCurrentSession();
  6.         } catch (HibernateException e) {
  7.             e.printStackTrace();
  8.         }
  9.     }

三。查询结构:

用一个RBAC的权限模型的一部分(USER,ROLE,USER_TO_ROLE )做例子


 

POJO如下:

  1. package model;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. /**
  5.  * User entity. @author MyEclipse Persistence Tools
  6.  */
  7. public class User  implements java.io.Serializable {
  8.     // Fields    
  9.      private Integer userId;
  10.      private Department department;
  11.      private String loginId;
  12.      private String password;
  13.      private String name;
  14.      private Set userToRoles = new HashSet(0);
  15.     // Constructors
  16.     /** default constructor */
  17.     public User() {
  18.     }
  19.     
  20.     /** full constructor */
  21.     public User(Department department, String loginId, String password, String name, Set userToRoles) {
  22.         this.department = department;
  23.         this.loginId = loginId;
  24.         this.password = password;
  25.         this.name = name;
  26.         this.userToRoles = userToRoles;
  27.     }
  28.    
  29.     // Property accessors
  30.     public Integer getUserId() {
  31.         return this.userId;
  32.     }
  33.     
  34.     public void setUserId(Integer userId) {
  35.         this.userId = userId;
  36.     }
  37.     public Department getDepartment() {
  38.         return this.department;
  39.     }
  40.     
  41.     public void setDepartment(Department department) {
  42.         this.department = department;
  43.     }
  44.     public String getLoginId() {
  45.         return this.loginId;
  46.     }
  47.     
  48.     public void setLoginId(String loginId) {
  49.         this.loginId = loginId;
  50.     }
  51.     public String getPassword() {
  52.         return this.password;
  53.     }
  54.     
  55.     public void setPassword(String password) {
  56.         this.password = password;
  57.     }
  58.     public String getName() {
  59.         return this.name;
  60.     }
  61.     
  62.     public void setName(String name) {
  63.         this.name = name;
  64.     }
  65.     public Set getUserToRoles() {
  66.         return this.userToRoles;
  67.     }
  68.     
  69.     public void setUserToRoles(Set userToRoles) {
  70.         this.userToRoles = userToRoles;
  71.     }
  72.    
  73. }
  1. package model;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. /**
  5.  * Role entity.
  6.  * 
  7.  * @author MyEclipse Persistence Tools
  8.  */
  9. public class Role implements java.io.Serializable {
  10.     // Fields
  11.     private Integer roleId;
  12.     private String roleName;
  13.     private String comment;
  14.     private Set userToRoles = new HashSet(0);
  15.     private Set roleToResources = new HashSet(0);
  16.     // Constructors
  17.     /** default constructor */
  18.     public Role() {
  19.     }
  20.     /** full constructor */
  21.     public Role(String roleName, String comment, Set userToRoles,
  22.             Set roleToResources) {
  23.         this.roleName = roleName;
  24.         this.comment = comment;
  25.         this.userToRoles = userToRoles;
  26.         this.roleToResources = roleToResources;
  27.     }
  28.     // Property accessors
  29.     public Integer getRoleId() {
  30.         return this.roleId;
  31.     }
  32.     public void setRoleId(Integer roleId) {
  33.         this.roleId = roleId;
  34.     }
  35.     public String getRoleName() {
  36.         return this.roleName;
  37.     }
  38.     public void setRoleName(String roleName) {
  39.         this.roleName = roleName;
  40.     }
  41.     public String getComment() {
  42.         return this.comment;
  43.     }
  44.     public void setComment(String comment) {
  45.         this.comment = comment;
  46.     }
  47.     public Set getUserToRoles() {
  48.         return this.userToRoles;
  49.     }
  50.     public void setUserToRoles(Set userToRoles) {
  51.         this.userToRoles = userToRoles;
  52.     }
  53.     public Set getRoleToResources() {
  54.         return this.roleToResources;
  55.     }
  56.     public void setRoleToResources(Set roleToResources) {
  57.         this.roleToResources = roleToResources;
  58.     }
  59. }
  1. package model;
  2. /**
  3.  * UserToRole entity.
  4.  * 
  5.  * @author MyEclipse Persistence Tools
  6.  */
  7. public class UserToRole implements java.io.Serializable {
  8.     // Fields
  9.     private Integer urId;
  10.     private User user;
  11.     private Role role;
  12.     private Integer projectId;
  13.     // Constructors
  14.     /** default constructor */
  15.     public UserToRole() {
  16.     }
  17.     /** full constructor */
  18.     public UserToRole(User user, Role role, Integer projectId) {
  19.         this.user = user;
  20.         this.role = role;
  21.         this.projectId = projectId;
  22.     }
  23.     // Property accessors
  24.     public Integer getUrId() {
  25.         return this.urId;
  26.     }
  27.     public void setUrId(Integer urId) {
  28.         this.urId = urId;
  29.     }
  30.     public User getUser() {
  31.         return this.user;
  32.     }
  33.     public void setUser(User user) {
  34.         this.user = user;
  35.     }
  36.     public Role getRole() {
  37.         return this.role;
  38.     }
  39.     public void setRole(Role role) {
  40.         this.role = role;
  41.     }
  42.     public Integer getProjectId() {
  43.         return this.projectId;
  44.     }
  45.     public void setProjectId(Integer projectId) {
  46.         this.projectId = projectId;
  47.     }
  48. }

生成的映射为:

User.hbm.xml
  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. <!-- 
  5.     Mapping file autogenerated by MyEclipse Persistence Tools
  6. -->
  7. <hibernate-mapping>
  8.     <class name="model.User" table="user" catalog="gov">
  9.         <id name="userId" type="java.lang.Integer">
  10.             <column name="USER_ID" />
  11.             <generator class="identity" />
  12.         </id>
  13.         <many-to-one name="department" class="model.Department" fetch="select">
  14.             <column name="DEPARTMENT_ID">
  15.                 <comment>ËùÔÚ²¿ÃÅ</comment>
  16.             </column>
  17.         </many-to-one>
  18.         <property name="loginId" type="java.lang.String">
  19.             <column name="LOGIN_ID" length="20" />
  20.         </property>
  21.         <property name="password" type="java.lang.String">
  22.             <column name="PASSWORD" length="20" />
  23.         </property>
  24.         <property name="name" type="java.lang.String">
  25.             <column name="NAME" length="20" />
  26.         </property>
  27.         <set name="userToRoles" inverse="true">
  28.             <key>
  29.                 <column name="USER_ID" />
  30.             </key>
  31.             <one-to-many class="model.UserToRole" />
  32.         </set>
  33.     </class>
  34. </hibernate-mapping>
Role.hbm.xml
  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. <!-- 
  5.     Mapping file autogenerated by MyEclipse Persistence Tools
  6. -->
  7. <hibernate-mapping>
  8.     <class name="model.Role" table="role" catalog="gov">
  9.         <id name="roleId" type="java.lang.Integer">
  10.             <column name="ROLE_ID" />
  11.             <generator class="identity" />
  12.         </id>
  13.         <property name="roleName" type="java.lang.String">
  14.             <column name="ROLE_NAME" length="40">
  15.                 <comment>ְλÃû</comment>
  16.             </column>
  17.         </property>
  18.         <property name="comment" type="java.lang.String">
  19.             <column name="COMMENT" length="200">
  20.                 <comment>ְλÃèÊö</comment>
  21.             </column>
  22.         </property>
  23.         <set name="userToRoles" inverse="true">
  24.             <key>
  25.                 <column name="ROLE_ID" />
  26.             </key>
  27.             <one-to-many class="model.UserToRole" />
  28.         </set>
  29.         <set name="roleToResources" inverse="true">
  30.             <key>
  31.                 <column name="ROLE_ID" />
  32.             </key>
  33.             <one-to-many class="model.RoleToResource" />
  34.         </set>
  35.     </class>
  36. </hibernate-mapping>
UserToRole.hbm.xml
  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. <!-- 
  5.     Mapping file autogenerated by MyEclipse Persistence Tools
  6. -->
  7. <hibernate-mapping>
  8.     <class name="model.UserToRole" table="user_to_role" catalog="gov">
  9.         <id name="urId" type="java.lang.Integer">
  10.             <column name="UR_ID" />
  11.             <generator class="identity" />
  12.         </id>
  13.         <many-to-one name="user" class="model.User" fetch="select">
  14.             <column name="USER_ID" />
  15.         </many-to-one>
  16.         <many-to-one name="role" class="model.Role" fetch="select">
  17.             <column name="ROLE_ID" />
  18.         </many-to-one>
  19.         <property name="projectId" type="java.lang.Integer">
  20.             <column name="PROJECT_ID" />
  21.         </property>
  22.     </class>
  23. </hibernate-mapping>

下面做了个TestCase。分别描述了HQL和SQL方式的查询,至于Criteria方式虽然比较面向对象,但是我不是很习惯:)

  1. package test;
  2. import java.util.List;
  3. import model.Role;
  4. import org.hibernate.HibernateException;
  5. import org.hibernate.SQLQuery;
  6. import org.hibernate.Session;
  7. import org.hibernate.SessionFactory;
  8. import org.hibernate.cfg.Configuration;
  9. import org.hibernate.type.IntegerType;
  10. import org.junit.After;
  11. import org.junit.Before;
  12. import org.junit.Test;
  13. public class TestCase {
  14.     Session session = null;
  15.     @Before
  16.     // 读取classpath下的配置文件hibernate.cfg.xml
  17.     // current_session_context_class=thread,show_sql=true
  18.     public void getSession() {
  19.         try {
  20.             Configuration cfg = new Configuration().configure();
  21.             SessionFactory sf = cfg.buildSessionFactory();
  22.             session = sf.getCurrentSession();
  23.         } catch (HibernateException e) {
  24.             e.printStackTrace();
  25.         }
  26.     }
  27.     /**
  28.      * 使用hql查询User_To_Role表中role_id字段
  29.      */
  30.     @Test
  31.     public void test() {
  32.         session.beginTransaction();
  33.         
  34.         String hql_findRole = "select role.roleId from UserToRole";
  35.         List list1 = session.createQuery(hql_findRole).list();
  36.         
  37.         session.getTransaction().commit();
  38.     }
  39.     
  40.     /**
  41.      * 使用sql语法查询返回表中一个字段,返回Hibernate包装的类型
  42.      */
  43.     @Test
  44.     public void SqlTest1() {
  45.         session.beginTransaction();
  46.         String sql_findRoleId = "select role_id from gov.user_to_role";
  47.         SQLQuery sq2 = session.createSQLQuery(sql_findRoleId).addScalar(
  48.                 "role_id"new IntegerType());
  49.         List list2 = sq2.list();
  50.         session.getTransaction().commit();
  51.     }
  52.     
  53.     /**
  54.      * 使用sql语法查询表,返回Hibernate包装的对象
  55.      */
  56.     @Test
  57.     public void sqlTest2() {
  58.         session.beginTransaction();
  59.         String sql_findRole = "select * from gov.role";
  60.         SQLQuery sq3 = session.createSQLQuery(sql_findRole).addEntity(
  61.                 Role.class);
  62.         List list3 = sq3.list();
  63.         
  64.         session.getTransaction().commit();
  65.     }
  66.     @After
  67.     public void clearDown() {
  68.         try {
  69.             // 这里session由于绑定事务到当前线程,在提交后自动关闭。
  70.             // 如果去掉下面2行注释,再次关闭就报错。
  71.             
  72.             // if (session != null) {
  73.             // session.close();
  74.             // }
  75.         } catch (HibernateException e) {
  76.             e.printStackTrace();
  77.         }
  78.     }
  79. }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics