Hibernate基础,基于Hibernate开发分布式

Posted Mr.Liu’blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate基础,基于Hibernate开发分布式相关的知识,希望对你有一定的参考价值。

 

Hibernate学习总结----

一、搭建Hibernate环境

使用Hibernate必须要导入3个jar包  在pom.xml中的<dependencies> </dependencies>中插入jar包

 

 

 1 <dependency>
 2       <groupId>org.hibernate</groupId>
 3       <artifactId>hibernate-core</artifactId>
 4       <version>3.5.0-Final</version>
 5     </dependency>
 6 
 7 
 8     <dependency>
 9       <groupId>org.slf4j</groupId>
10       <artifactId>slf4j-log4j12</artifactId>
11       <version>1.5.8</version>
12     </dependency>
13 
14 
15     <dependency>
16       <groupId>org.javassist</groupId>
17       <artifactId>javassist</artifactId>
18       <version>3.13.0-GA</version>
19     </dependency>

 

 

 

1.在src目录下创建hibernate.cfg.xml配置文件  没有数据库的话要创建数据库,表会自动建

PS:文件的名字不能改!

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration
 3         PUBLIC "-//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="hbm2ddl.auto">update</property><!--自动生成数据库表-->
 8         <property name="dialect">org.hibernate.dialect.mysqlDialect</property><!--数据库方言-->
 9         <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
10         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
11         <property name="connection.username">root</property>
12         <property name="connection.password">1234</property>
13         <!--设置输出sql语句 若为true,表示在程序运行时,将在控制台输出SQL语句默认false-->
14         <property name="show_sql">true</property>
15         <mapping resource="hbm/user.hbm.xml"/><!--加载映射文件-->
16     </session-factory>
17 </hibernate-configuration>

 

2. 编写实体类,以User类为例

 1 package cn.yunhe.entity;
 2 
 3 import java.util.Date;
 4 
 5 /**
 6  * Created by Administrator on 2017/7/4.
 7  */
 8 public class User {
 9     private int userid;//用户id
10     private String uname;//用户名
11     private String upwd;//密码
12     private int age;//年龄
13     private Date hiredate;//注册日期
14 
15     public Date getHiredate() {
16         return hiredate;
17     }
18 
19     public void setHiredate(Date hiredate) {
20         this.hiredate = hiredate;
21     }
22 
23     public int getUserid() {
24         return userid;
25     }
26 
27     public void setUserid(int userid) {
28         this.userid = userid;
29     }
30 
31     public String getUname() {
32         return uname;
33     }
34 
35     public void setUname(String uname) {
36         this.uname = uname;
37     }
38 
39     public String getUpwd() {
40         return upwd;
41     }
42 
43     public void setUpwd(String upwd) {
44         this.upwd = upwd;
45     }
46 
47     public int getAge() {
48         return age;
49     }
50 
51     public void setAge(int age) {
52         this.age = age;
53     }
54 }

3.创建映射文件   hbm/user.hbm.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 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>
 7     <class name="cn.yunhe.entity.User" table="t_user">
 8         <id name="userid" type="java.lang.Integer">
 9             <column name="userid"/>
10             <!--mysql用identity -->
11             <generator class="identity"/>
12             <!--oracle用sequence-->
13            <!-- <generator class="sequence">
14                 <param name="sequence">SEQ_ID</param>
15             </generator>-->
16             <!--不知道是mysql还是Oracle就用native 如果是Oracle它会自动创建序列,如果是mysql它也能用-->
17             <!--<generator class="native"/>-->
18         </id>
19         <property name="uname" type="java.lang.String">
20             <column name="uname" length="20"/>
21         </property>
22         <property name="upwd" type="java.lang.String">
23             <column name="upwd" length="20"/>
24         </property>
25         <property name="age" type="java.lang.Integer">
26             <column name="age"/>
27         </property>
28         <property name="hiredate" type="java.util.Date">
29             <column name="hiredate"/>
30         </property>
31      </class>
32 </hibernate-mapping>

4.创建测试类Demo

 1 import cn.yunhe.entity.User;
 2 import org.hibernate.Session;
 3 import org.hibernate.SessionFactory;
 4 import org.hibernate.Transaction;
 5 import org.hibernate.cfg.Configuration;
 6 import org.junit.After;
 7 import org.junit.Before;
 8 import org.junit.Test;
 9 
10 import java.util.Date;
11 
12 /**
13  * 测试类
14  * Created by Administrator on 2017/7/4.
15  */
16 public class demo  {
17     Session session=null;//Session接口:负责保存、更新、删除、加载以及查询对象
18     Transaction tr=null;//管理事务 执行增删改操作后要 tr.comment();
19 
20     @Before
21     //目标方法前的方法  用与获得session
22     public void setUp() throws Exception{
23         //获得Hibernate配置管理接口Configuration
24         Configuration configuration=new Configuration().configure();
25         //根据Configuration实例创建session的工厂类SessionFactory
26         SessionFactory factory=configuration.buildSessionFactory();
27         //通过session工厂获得session实例
28         session=factory.openSession();
29     }
30 
31     @Test
32     //添加用户
33     public void testSave(){
34         tr=session.beginTransaction();//在单元测试的setUp()方法中获得session对象,开启事务
35         User user=new User();
36         user.setUname("弗拉基米尔");
37         user.setUpwd("1234");
38         user.setAge(1000);
39         user.setHiredate(new Date());
40         session.save(user);//执行添加功能,会自动建表
41         tr.commit();//提交事务
42     }
43     @Test
44     //查询用户
45     public void testFindById(){
46         //get里第一个参数是实体类,第二个参数是所要查询的用户id
47         User user=(User) session.get(User.class,new Integer(2));
48         System.out.println("用户id:"+user.getUserid());
49         System.out.println("用户名:"+user.getUname());
50         System.out.println("密码:"+user.getUpwd());
51         System.out.println("年龄:"+user.getAge());
52         System.out.println("注册日期:"+user.getHiredate());
53         //查询不用提交事务  tearDown会关闭session
54     }
55 
56     @Test
57     //修改用户  实际上是根据id查,改了再修改
58     public void testModify(){
59         tr=session.beginTransaction();///在单元测试的setUp()方法中获得session对象
60         //先根据id查询出来要修改的数据
61         User user=(User) session.get(User.class,new Integer(2));
62         //把要修改的内容放入 user中
63         user.setAge(600);
64         session.update(user); //可以省略
65         tr.commit();//提交事务
66     }
67 
68     @Test
69     //删除用户
70     public void testDel(){
71         tr=session.beginTransaction();
72         //根据id查出来,然后再删除
73         User user=(User)session.get(User.class,2);
74         session.delete(user);
75         tr.commit();
76     }
77 
78     @After
79     //目标方法后的方法 用于关闭sesseion 对象
80     public void tearDown() throws Exception{
81         session.close();
82     }
83 }

二、主键生成策略

identity:使用数据库的自动增长策略,不是所有数据库都支持,比如oracle就不支持。

sequence:在 DB2,PostgreSQL,Oracle,SAP DB,McKoi 中使用序列(sequence)在使用Oracle数据库时可以使用这一个。

hilo:使用高低位算法生成主键值。只需要一张额外表,所有的数据都支持。

native:根据底层数据库的能力选择 identity、sequence 或者 hilo中的一个。

assigned:手工指定主键值。

uuid:由Hibernate自动生成UUID并指定为主键值。

三、Hibernate映射关系配置

1.一对一映射(以主键关联作为示例)User与IdCard(有外键方)的XML配置:

 
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping package="test.Hibernate.model">
    <class name="User" table="user">
        <id name="id" type="int" column="id">
            <generator class="native"></generator>
        </id>
        
        <property name="name" type="string" column="name"/>        
        
         <set name="address" table="address">    
            <key column="userId"></key>
            <element column="address" type="string"></element>
        </set>
        
        <one-to-one name="idCard" class="IdCard" cascade="all"></one-to-one>     
    </class>
</hibernate-mapping>
 
 
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping package="test.Hibernate.model">
    <class name="IdCard" table="idCard">
        <id name="id" type="int" column="id">
            <generator class="foreign">
                <param name="property">user</param>
            </generator>
        </id>
        <property name="number" type="string" column="number"/>        
        <one-to-one name="user" class="User" constrained="true"></one-to-one>
        
    </class>
</hibernate-mapping>
 

2.一对多,多对一(以qx(区县)和jd(街道)为例)外键要设置可以为空,不然不能进行插入数据

(1)Jd.hbm.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC
 3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4         "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 5 <hibernate-mapping>
 6     <class name="cn.yunhe.model.Jd" table="jd">
 7         <id name="jdid" column="jdid" type="java.lang.Integer">
 8             <generator class="native"/>
 9         </id>
10         <property name="jdname" column="jdname" type="java.lang.String"/>
11 
12         <!--多对一-->
13         <many-to-one name="qx" class="cn.yunhe.model.Qx" column="qxid"/>
14 
15     </class>
16 </hibernate-mapping>

(2) Qx.hbm.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC
 3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4         "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 5 <hibernate-mapping>
 6     <class name="cn.yunhe.model.Qx" table="qx">
 7         <id name="qxid" column="qxid" type="java.lang.Integer">
 8             <generator class="native"/>
 9         </id>
10         <property name="qxname" column="qxname"/>
11 
12         <set name="jds" inverse="false" cascade="all">   <!--反转-->
13             <key column="qxid"/>
14             <one-to-many class="cn.yunhe.model.Jd"/>
15         </set>
16 
17     </class>
18 
19 </hibernate-mapping>

(3) Demo

  1 import cn.yunhe.model.Jd;
  2 import cn.yunhe.model.Qx;
  3 import org.hibernate.Session;
  4 import org.hibernate.SessionFactory;
  5 import org.hibernate.Transaction;
  6 import org.hibernate.cfg.Configuration;
  7 import org.junit.After;
  8 import org.junit.Before;
  9 import org.junit.Test;
 10 
 11 import java.util.Iterator;
 12 
 13 /**
 14  * Created by Administrator on 2017/7/5.
 15  */
 16 public class Demo {
 17 
 18     Session session=null;
 19     Transaction tr=null;
 20 
 21     @Before
 22     public void setUp(){
 23         //获得session
 24         Configuration config=new Configuration().configure();
 25         SessionFactory factory=config.buildSessionFactory();
 26         session=factory.openSession();
 27         tr=session.beginTransaction();
 28     }
 29 
 30     @Test
 31     //多对一查询
 32     public void manyToOne(){
 33         //查询出街道以及对应的区县
 34         Jd jd = (Jd) session.get(Jd.class,1);
 35         String qxname = jd.getQx().getQxname();
 36 
 37         System.out.println("街道:" + jd.getJdname() + "所在的区县是:" + qxname);
 38 
 39     }
 40 
 41     @Test
 42     //一对多查询
 43     public void oneToMany(){
 44         //查询出一个区县下的所有街道
 45         Qx qx=(Qx)session.get(Qx.class,1);//查出区县
 46         System.out.println("区县"+qx.getQxname()+"下有:");
 47         //遍历输出qx的属性jds中所有的jd对象
 48         Iterator<Jd> it =qx.getJds().iterator();
 49         while (it.hasNext()){
 50             Jd jd=it.next();
 51             System.out.println(jd.getJdname());
 52         }
 53     }
 54 
 55     @Test
 56     //在one一方添加数据 增加一个区县:黄河区
 57     public void testAddOne(){
 58         Qx qx=new Qx();
 59         qx.setQxname("黄河区");
 60         session.save(qx);
 61         tr.commit();
 62     }
 63 
 64     @Test
 65     //在many一方添加数据 增加山南区下属的三个街道:“和平路”、“八一路”和“五四大道”
 66     //有一点要注意,应设置外键可以为null
 67     public voidJsp标签字典开发_基于Spring+Hibernate

hibernate基础10:关联映射之基于主键的双向一对一

hibernate基础10:关联映射之基于主键的双向一对一

java web开发入门三(Hibernate)基于intellig idea

hibernate基础08:关联映射之基于外键的双向一对一

hibernate基础07:关联关系映射之基于外键单向一对一