首先要感谢满江红社区:)给我们翻译了大量高质量的文档,我学习hibernate的文档资料主要来自他们的贡献。
对Hibernate概念模糊的一定要去看看 夏昕 写的《Hibernate 开发指南 》
一。Hibernate最小依赖包
手动添加每个项目的最小依赖包,并认识每个jar的大体作用是很有必要的:)
二、加载方式与核心类
1.加载Session
Session是持久层操作的基础,相当于JDBC中的 Connection。(注意Hibernate3中使用了与Hibernate2中不同的Session。老式的Session被迁移到org.hibernate.classic.Session)
Hibernate3以后应该使用如下的加载代码,可以获得绑定线程的Session变量。
- public void getSession() {
- try {
- Configuration cfg = new Configuration().configure();
- SessionFactory sf = cfg.buildSessionFactory();
- session = sf.getCurrentSession();
- } catch (HibernateException e) {
- e.printStackTrace();
- }
- }
三。查询结构:
用一个RBAC的权限模型的一部分(USER,ROLE,USER_TO_ROLE )做例子
POJO如下:
- package model;
- import java.util.HashSet;
- import java.util.Set;
- /**
- * User entity. @author MyEclipse Persistence Tools
- */
- public class User implements java.io.Serializable {
- // Fields
- private Integer userId;
- private Department department;
- private String loginId;
- private String password;
- private String name;
- private Set userToRoles = new HashSet(0);
- // Constructors
- /** default constructor */
- public User() {
- }
- /** full constructor */
- public User(Department department, String loginId, String password, String name, Set userToRoles) {
- this.department = department;
- this.loginId = loginId;
- this.password = password;
- this.name = name;
- this.userToRoles = userToRoles;
- }
- // Property accessors
- public Integer getUserId() {
- return this.userId;
- }
- public void setUserId(Integer userId) {
- this.userId = userId;
- }
- public Department getDepartment() {
- return this.department;
- }
- public void setDepartment(Department department) {
- this.department = department;
- }
- public String getLoginId() {
- return this.loginId;
- }
- public void setLoginId(String loginId) {
- this.loginId = loginId;
- }
- public String getPassword() {
- return this.password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Set getUserToRoles() {
- return this.userToRoles;
- }
- public void setUserToRoles(Set userToRoles) {
- this.userToRoles = userToRoles;
- }
- }
- package model;
- import java.util.HashSet;
- import java.util.Set;
- /**
- * Role entity.
- *
- * @author MyEclipse Persistence Tools
- */
- public class Role implements java.io.Serializable {
- // Fields
- private Integer roleId;
- private String roleName;
- private String comment;
- private Set userToRoles = new HashSet(0);
- private Set roleToResources = new HashSet(0);
- // Constructors
- /** default constructor */
- public Role() {
- }
- /** full constructor */
- public Role(String roleName, String comment, Set userToRoles,
- Set roleToResources) {
- this.roleName = roleName;
- this.comment = comment;
- this.userToRoles = userToRoles;
- this.roleToResources = roleToResources;
- }
- // Property accessors
- public Integer getRoleId() {
- return this.roleId;
- }
- public void setRoleId(Integer roleId) {
- this.roleId = roleId;
- }
- public String getRoleName() {
- return this.roleName;
- }
- public void setRoleName(String roleName) {
- this.roleName = roleName;
- }
- public String getComment() {
- return this.comment;
- }
- public void setComment(String comment) {
- this.comment = comment;
- }
- public Set getUserToRoles() {
- return this.userToRoles;
- }
- public void setUserToRoles(Set userToRoles) {
- this.userToRoles = userToRoles;
- }
- public Set getRoleToResources() {
- return this.roleToResources;
- }
- public void setRoleToResources(Set roleToResources) {
- this.roleToResources = roleToResources;
- }
- }
- package model;
- /**
- * UserToRole entity.
- *
- * @author MyEclipse Persistence Tools
- */
- public class UserToRole implements java.io.Serializable {
- // Fields
- private Integer urId;
- private User user;
- private Role role;
- private Integer projectId;
- // Constructors
- /** default constructor */
- public UserToRole() {
- }
- /** full constructor */
- public UserToRole(User user, Role role, Integer projectId) {
- this.user = user;
- this.role = role;
- this.projectId = projectId;
- }
- // Property accessors
- public Integer getUrId() {
- return this.urId;
- }
- public void setUrId(Integer urId) {
- this.urId = urId;
- }
- public User getUser() {
- return this.user;
- }
- public void setUser(User user) {
- this.user = user;
- }
- public Role getRole() {
- return this.role;
- }
- public void setRole(Role role) {
- this.role = role;
- }
- public Integer getProjectId() {
- return this.projectId;
- }
- public void setProjectId(Integer projectId) {
- this.projectId = projectId;
- }
- }
生成的映射为:
User.hbm.xml
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <!--
- Mapping file autogenerated by MyEclipse Persistence Tools
- -->
- <hibernate-mapping>
- <class name="model.User" table="user" catalog="gov">
- <id name="userId" type="java.lang.Integer">
- <column name="USER_ID" />
- <generator class="identity" />
- </id>
- <many-to-one name="department" class="model.Department" fetch="select">
- <column name="DEPARTMENT_ID">
- <comment>ËùÔÚ²¿ÃÅ</comment>
- </column>
- </many-to-one>
- <property name="loginId" type="java.lang.String">
- <column name="LOGIN_ID" length="20" />
- </property>
- <property name="password" type="java.lang.String">
- <column name="PASSWORD" length="20" />
- </property>
- <property name="name" type="java.lang.String">
- <column name="NAME" length="20" />
- </property>
- <set name="userToRoles" inverse="true">
- <key>
- <column name="USER_ID" />
- </key>
- <one-to-many class="model.UserToRole" />
- </set>
- </class>
- </hibernate-mapping>
Role.hbm.xml
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <!--
- Mapping file autogenerated by MyEclipse Persistence Tools
- -->
- <hibernate-mapping>
- <class name="model.Role" table="role" catalog="gov">
- <id name="roleId" type="java.lang.Integer">
- <column name="ROLE_ID" />
- <generator class="identity" />
- </id>
- <property name="roleName" type="java.lang.String">
- <column name="ROLE_NAME" length="40">
- <comment>ְλÃû</comment>
- </column>
- </property>
- <property name="comment" type="java.lang.String">
- <column name="COMMENT" length="200">
- <comment>ְλÃèÊö</comment>
- </column>
- </property>
- <set name="userToRoles" inverse="true">
- <key>
- <column name="ROLE_ID" />
- </key>
- <one-to-many class="model.UserToRole" />
- </set>
- <set name="roleToResources" inverse="true">
- <key>
- <column name="ROLE_ID" />
- </key>
- <one-to-many class="model.RoleToResource" />
- </set>
- </class>
- </hibernate-mapping>
UserToRole.hbm.xml
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <!--
- Mapping file autogenerated by MyEclipse Persistence Tools
- -->
- <hibernate-mapping>
- <class name="model.UserToRole" table="user_to_role" catalog="gov">
- <id name="urId" type="java.lang.Integer">
- <column name="UR_ID" />
- <generator class="identity" />
- </id>
- <many-to-one name="user" class="model.User" fetch="select">
- <column name="USER_ID" />
- </many-to-one>
- <many-to-one name="role" class="model.Role" fetch="select">
- <column name="ROLE_ID" />
- </many-to-one>
- <property name="projectId" type="java.lang.Integer">
- <column name="PROJECT_ID" />
- </property>
- </class>
- </hibernate-mapping>
下面做了个TestCase。分别描述了HQL和SQL方式的查询,至于Criteria方式虽然比较面向对象,但是我不是很习惯:)
- package test;
- import java.util.List;
- import model.Role;
- import org.hibernate.HibernateException;
- import org.hibernate.SQLQuery;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import org.hibernate.type.IntegerType;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
- public class TestCase {
- Session session = null;
- @Before
- // 读取classpath下的配置文件hibernate.cfg.xml
- // current_session_context_class=thread,show_sql=true
- public void getSession() {
- try {
- Configuration cfg = new Configuration().configure();
- SessionFactory sf = cfg.buildSessionFactory();
- session = sf.getCurrentSession();
- } catch (HibernateException e) {
- e.printStackTrace();
- }
- }
- /**
- * 使用hql查询User_To_Role表中role_id字段
- */
- @Test
- public void test() {
- session.beginTransaction();
- String hql_findRole = "select role.roleId from UserToRole";
- List list1 = session.createQuery(hql_findRole).list();
- session.getTransaction().commit();
- }
- /**
- * 使用sql语法查询返回表中一个字段,返回Hibernate包装的类型
- */
- @Test
- public void SqlTest1() {
- session.beginTransaction();
- String sql_findRoleId = "select role_id from gov.user_to_role";
- SQLQuery sq2 = session.createSQLQuery(sql_findRoleId).addScalar(
- "role_id", new IntegerType());
- List list2 = sq2.list();
- session.getTransaction().commit();
- }
- /**
- * 使用sql语法查询表,返回Hibernate包装的对象
- */
- @Test
- public void sqlTest2() {
- session.beginTransaction();
- String sql_findRole = "select * from gov.role";
- SQLQuery sq3 = session.createSQLQuery(sql_findRole).addEntity(
- Role.class);
- List list3 = sq3.list();
- session.getTransaction().commit();
- }
- @After
- public void clearDown() {
- try {
- // 这里session由于绑定事务到当前线程,在提交后自动关闭。
- // 如果去掉下面2行注释,再次关闭就报错。
- // if (session != null) {
- // session.close();
- // }
- } catch (HibernateException e) {
- e.printStackTrace();
- }
- }
- }