xoxobool

成功者,永远成功,失败者,永远失败,我要面对者,走向成功!

导航

Hibernate的配置文件以及用法

一. 三大框架

Hibernate

1.安装hibernate插件至ecilpse

2.进行配置

 2.1 主配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
 <!-- 数据库连接 -->
  <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.password">laoer123</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
  <property name="hibernate.connection.username">test0816</property>
  <!-- 数据库方案 -->
  <property name="hibernate.default_schema">TEST0816</property>
  <!-- 数据库方言 -->
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <!-- 调试 -->
  <property name="hibernate.format_sql">true</property>
  <property name="hibernate.show_sql">true</property>
  <!-- 自动建表方式 -->
  <property name="hibernate.hbm2ddl.auto">update</property>
  <!-- 映射文件 -->
  <mapping resource="com/hanqi/entity/User.hbm.xml"/>
  <mapping resource="com/hanqi/entity/Student.hbm.xml"/>
   <mapping resource="com/hanqi/entity/Person.hbm.xml"/>
   <mapping resource="com/hanqi/entity/Course.hbm.xml"/>
   <mapping resource="com/hanqi/entity/Teacher.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

2.21 创建持久化类

package com.hanqi.entity;

import java.util.Date;

//实体化类
//不要使用final修饰
public class User {
    
    private Integer userID;
    private String userName;
    private Date birthday;
    private Double money;
    private String password;
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Integer getUserID() {
        return userID;
    }
    public void setUserID(Integer userID) {
        this.userID = userID;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public Double getMoney() {
        return money;
    }
    public void setMoney(Double money) {
        this.money = money;
    }
    // 必须提供无参的构造方法
    //需要用到反射
    public User() {
        super();
        }
    public User(Integer userID, String userName) {
        super();
        this.userID = userID;
        this.userName = userName;
        }
    @Override
    public String toString() {
        return "User [userID=" + userID + ", userName=" + userName + ", birthday=" + birthday + ", money=" + money
                + ", password=" + password + "]";
    }

    
}

2.22 创建持久化类的映射文件

创建方法 new - other-hibernate-Mapping file

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-11-7 14:40:01 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.hanqi.entity.User" table="T_USER">
        <id name="userID" type="int">
            <column name="USER_ID" />
            <generator class="native" />
        </id>
        <property name="userName" type="java.lang.String">
            <column name="USER_NAME" length="20" not-null="true" unique="true"/>
        </property>
        <property name="birthday" type="java.util.Date">
            <column name="BIRTHDAY" sql-type="DATE"/>
        </property>
        <property name="money" type="java.lang.Double">
            <column name="MONEY" sql-type="NUMBER" default="0" length="8" scale="2"/>
        </property>
         <property name="password" type="java.lang.String">
        <column name="PASSWORD" length="10"></column>
        </property> 
        
    </class>
</hibernate-mapping>

3 测试用例的用法

package com.hanqi.test;



import java.util.Date;
//import java.util.List;
import java.util.List;

//import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.hanqi.entity.Course;
import com.hanqi.entity.Student;
import com.hanqi.entity.Teacher;
import com.hanqi.entity.User;

public class Test01 {
    
    private SessionFactory sf = null;
    private Session se=null;
    private Transaction ts=null;
    // 在测试用例方法被执行之前,自动执行的方法
    // 一般用来初始化公用的对象
    //前置方法
    
    @Before
    public void init()
    {
        //1 获取配置文件
        Configuration cfg= new Configuration().configure();
        //2 注册配置
        ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
        //3 获取SessionFactory(相当于JDBC的连接)
        sf=cfg.buildSessionFactory(sr);
        System.out.println(sf);
        //4 产生Session
        se= sf.openSession();
        //5 启动事务
        ts=se.beginTransaction();
    }
    //后置方法
    //一般用来释放资源
    @After
    public void destory()
    {
        //7 提交事务
        ts.commit();
        //8 释放资源
        se.close();
        sf.close();
    }
    //测试Hibernate连接数据库
    @Test
    public void test() {
    

        //6 操作数据库
        //添加数据
        
        //实例化的新对象,处于临时状态
        User u1 = new User();
        u1.setBirthday(new Date());
        u1.setMoney(2000.0);
        u1.setPassword("123456");
        u1.setUserName("测试1");
        //u1.setUserID(4);//自然主键 assigned
        
        //保存数据
        //通过save方法,把对象从临时状态转成持久化状态
        se.save(u1);
        System.out.println(u1);
    
    }  
    //测试查询的方法
    @Test
    public void test1()
    {
        // 查询数据
        // 提供2个参数
        // 需要返回哪一个持久化类的实例
        // 实例的标识(数据的主键值)
        //通过Session的get方法获得的对象处于持久化状态
        User u2=(User)se.get(User.class, 3);
        u2.setUserName("修改的");
        System.out.println(u2);
        //删除
        se.delete(u2); //使持久化对象进入删除状态
    }

4 反向工程的用法

4.1 创建Hibernate Console Configuration

目的是创建数据库连接一般选择项目的配置文件hibernate.cfg.xml获取连接信息

4.2 创建反向的配置文件 hibernate.reveng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >

<hibernate-reverse-engineering>
  <table-filter match-name="STUDENT"/>
  <table-filter match-name="PERSON"/>
    <table-filter match-name="TEACHER"/>
      <table-filter match-name="COURSE"/>
</hibernate-reverse-engineering>

4.3配置Code Generation 并运行

1.连接数据库的Console Configuration
2.反向配置文件 .reveng.xml
3.要输出的项目目录
4.一般是项目的src目录
5.要生成的包名
6.要导出的文件类型
7.持久化类
8.映射文件

4.4 不要忘记在主配置文件中去配置一下

5 HQL Hibernate Query Language 一种面向对象的查询语句

public void test5()
    {
        //使用HQL
        //创建Query对象
//        Query qu=se.createQuery("from User where userID < ? and userName = :uname order by userID desc");
//        //设置占位符
//        qu.setInteger(0, 6);
//        //按照参数名方式设置
//        qu.setString("uname", "测试1");
//        //执行查询
//        List<User>lu=qu.list();
//        //方法链调用
//        lu = se.createQuery("from User where userID < ?")
//                .setInteger(0, 6)
//                .list();
//        for(User u:lu)
//        {
//            System.out.println(u);
//        }
//        
        se.createQuery("from User where userID < ? and userName = :uname order by userID desc")
          .setInteger(0, 6)
          .setString("uname", "测试1")
          .list()
          .stream()
          .forEach(System.out::println);
        
    }
    //测试分页
            @Test
            public void test6()
            {
                // 设置开始行号:页码 =2
                // (页码 -1) * 每页行数
                @SuppressWarnings("unchecked")
                List<User> lu = se.createQuery("from User order by userID")
                        .setMaxResults(5)
                        .setFirstResult(5)
                        .list();
                for(User u:lu)
                {
                        System.out.println(u);
                }
            }
    //分组查询
            @SuppressWarnings("unchecked")
            @Test
            //单列不需要数组
            //多列用数组表示
            public void test7()
            {
            List<Object[]>lo=se.createQuery("select userName,count(1) from User group by userName")
                .list();
            
            for(Object[] o:lo)
            {
                System.out.println(o[0]+" "+o[1]);
            }
            }
            //测试投影查询
            @SuppressWarnings("unchecked")
            @Test
            public void test8()
            {
                List<Object[]>lo=se.createQuery("select userID,userName from User")
                .list();
                for(Object[] obj :lo)
                {
                    System.out.println(obj[0]+" "+obj[1]);
                }
                System.out.println("******************************");
                // 返回持久化对象的集合
                List<User> lu = se.createQuery("select new User(userID,userName) from User")
                         .list();
                for(User u:lu)
                {
                    System.out.println(u);
                    
                    se.update(u);
                }
            }
            //测试新的类
            @Test
            public void test9()
            {
                Student st = (Student)se.get(Student.class, "108");
                System.out.println(st);
            }
            //测试多对一
            @Test
            public void test10()
            {
                Course cs = (Course)se.get(Course.class, "9-888");
                
                System.out.println(cs);
            }
            //测试一对多
            @Test
            public void test11()
            {
                Teacher te=(Teacher)se.get(Teacher.class, "831");
                System.out.println(te);
                se.delete(te);
            }
            

 

posted on 2016-11-13 18:31  春之林木  阅读(3220)  评论(0编辑  收藏  举报