Java开发知识点Java学习笔记

Hibernate框架(1) - 配置文件

2017-04-09  本文已影响147人  奋斗的老王

ORM概念

初识Hibernate

public class Employee {
    private int empId;
    private String empName;
    private Date workDate;
}
- Employee.hbm.xml : 对象的映射
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.itcast.a_hello">
    <class name="Employee" table="employee">
        <!-- 主键 ,映射-->
        <id name="empId" column="id">
            <generator class="native"/>
        </id>
        <!-- 非主键,映射 -->
        <property name="empName" column="empName"></property>
        <property name="workDate" column="workDate"></property>
    </class>
</hibernate-mapping>
- hibernate.cfg.xml : 主配置文件
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>

        <!-- 数据库连接配置 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///hib_demo</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        
        <property name="hibernate.show_sql">true</property>
        
        <!-- 加载所有映射 -->
        <mapping resource="cn/itcast/a_hello/Employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
- App.java   测试类
public class App {
    @Test
    public void testHello() throws Exception {
        // 对象
        Employee emp = new Employee();
        emp.setEmpName("班长");
        emp.setWorkDate(new Date());

        // 获取加载配置文件的管理类对象
        Configuration config = new Configuration();
        config.configure();  // 默认加载src/hibenrate.cfg.xml文件
        // 创建session的工厂对象
        SessionFactory sf = config.buildSessionFactory();
        // 创建session (代表一个会话,与数据库连接的会话)
        Session session = sf.openSession();
        // 开启事务
        Transaction tx = session.beginTransaction();
        //保存-数据库
        session.save(emp);
        // 提交事务
        tx.commit();
        // 关闭
        session.close();
        sf.close();
      }
}

Hibernate Api

|-- Transaction hibernate事务对象

Hibernate crud

public class EmployeeDaoImpl implements IEmployeeDao{

    @Override
    public Employee findById(Serializable id) {
        Session session = null;
        Transaction tx = null;
        try {
            // 获取Session
            session = HibernateUtils.getSession();
            // 开启事务
            tx = session.beginTransaction();
            // 主键查询
            return (Employee) session.get(Employee.class, id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }
    }

    @Override
    public List<Employee> getAll() {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            // HQL查询
            Query q = session.createQuery("from Employee");
            return q.list();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }
    }

    @Override
    public List<Employee> getAll(String employeeName) {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            Query q =session.createQuery("from Employee where empName=?");
            // 注意:参数索引从0开始
            q.setParameter(0, employeeName);
            // 执行查询
            return q.list();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }
    }

    @Override
    public List<Employee> getAll(int index, int count) {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            Query q = session.createQuery("from Employee");
            // 设置分页参数
            q.setFirstResult(index);  // 查询的其实行 
            q.setMaxResults(count);   // 查询返回的行数
            
            List<Employee> list = q.list();
            return list;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }
    }

    @Override
    public void save(Employee emp) {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            // 执行保存操作
            session.save(emp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }
        
    }

    @Override
    public void update(Employee emp) {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            session.update(emp);
            
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }
        
    }

    @Override
    public void delete(Serializable id) {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSession();
            tx = session.beginTransaction();
            // 先根据id查询对象,再判断删除
            Object obj = session.get(Employee.class, id);
            if (obj != null) {
                session.delete(obj);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            tx.commit();
            session.close();
        }
    }
}

Hibernate.cfg.xml 主配置

public class App_ddl {

    // 自动建表
    @Test
    public void testCreate() throws Exception {
        // 创建配置管理类对象
        Configuration config = new Configuration();
        // 加载主配置文件
        config.configure();
        
        // 创建工具类对象
        SchemaExport export = new SchemaExport(config);
        // 建表
        // 第一个参数: 是否在控制台打印建表语句
        // 第二个参数: 是否执行脚本
        export.create(true, true);
    }
}

映射配置

  1. 普通字段类型
  2. 主键映射
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 映射文件: 映射一个实体类对象;  描述一个对象最终实现可以直接保存对象数据到数据库中。  -->
<!-- 
  package: 要映射的对象所在的包(可选,如果不指定,此文件所有的类都要指定全路径)
  auto-import 默认为true, 在写hql的时候自动导入包名;如果指定为false, 再写hql的时候必须要写上类的全名(eg:session.createQuery("from sh.anderson.c_hbm_config.Employee").list(); )
 -->
<hibernate-mapping package="sh.anderson.c_hbm_config" auto-import="true">

    <!-- 
      class 映射某一个对象的(一般情况,一个对象写一个映射文件,即一个class节点)
      name 指定要映射的对象的类型
      table 指定对象对应的表; 如果没有指定表名,默认与对象名称一样 
    -->
    <class name="Employee" table="employee">    
        <!-- 主键 ,映射-->
        <id name="empId" column="id">
            <!-- 主键的生成策略 : 
                identity  自增长(mysql,db2)
                sequence  自增长(序列), oracle中自增长是以序列方法实现
                native  自增长【会根据底层数据库自增长的方式选择identity或sequence】; 如果是mysql数据库, 采用的自增长方式是identity; 如果是oracle数据库, 使用sequence序列的方式实现自增长  
                increment  自增长(会有并发访问的问题,一般在服务器集群环境使用会存在问题) 
                assigned  指定主键生成策略为手动指定主键的值
                uuid      指定uuid随机生成的唯一的值
                foreign   (外键的方式, one-to-one讲)
             -->
            <generator class="uuid"/>
        </id>
        
        <!-- 普通字段映射 - > property
            name  指定对象的属性名称
            column 指定对象属性对应的表的字段名称,如果不写默认与对象属性一致
            length 指定字符的长度, 默认为255
            type   指定映射表的字段的类型,如果不指定会匹配属性的类型
                java类型:     必须写全名
                hibernate类型:  直接写类型,都是小写
        -->
        <property name="empName" column="empName" type="java.lang.String" length="20"></property>
        <property name="workDate" type="java.util.Date"></property>
        <!-- 如果列名称为数据库关键字,需要用反引号或改列名。 -->
        <property name="desc" column="`desc`" type="java.lang.String"></property>
        
    </class>
</hibernate-mapping>

复合主键映射

// implements Serializable 一定要实现序列化, 否则取出数据报错
public class CompositeKeys implements Serializable{
    private String userName;
    private String address;
   // .. get/set
}
public class User {
    // 名字跟地址,不会重复
    private CompositeKeys keys;
    private int age;
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.itcast.d_compositeKey" auto-import="true">
    
    <class name="User">
        <!-- 复合主键映射 -->
        <composite-id name="keys">
            <key-property name="userName" type="string"></key-property>
            <key-property name="address" type="string"></key-property>
        </composite-id>
        
        <property name="age" type="int"></property>     
        
    </class>
</hibernate-mapping>
上一篇 下一篇

猜你喜欢

热点阅读