Hibernate入门

ORM(Object/Relationship Mapping): 对象/关系映射
写SQL语句有什么不好吗?
1. 不同的数据库使用的SQL语法不同。比如PL/SQL与T/SQL
2. 同样的功能在不同的数据库中有不同的实现方式。比如分页SQL
3. 程序过分依赖SQL对程序的移植和扩展、维护带来很大的麻烦

Hibernate简介

Hibernate是Java领域的一款开源的ORM框架技术。
Hibernate对JDBC进行了非常轻量级的对象封装。
其它的主流ORM框架技术:

  • MyBatis - 前身就是著名的iBatis
  • Toplink - 被Oracle收购,并重新包装为Oracle AS TopLink
  • EJB- 本身是JavaEE的规范

推荐安装Eclipse插件:Hibernate Tools for Eclipse Plugins

编写Hibernate的步骤
1. 创建Hibernate的配置文件 hibernate.cfg.xml
2. 创建持久化类
3. 创建对象-关系映射文件
4. 通过Hibernate API编写访问数据库的代码

导入的包
1. 导入Hibernate必须的jar包 位于lib\required
2. 导入Mysql的JDBC驱动
3. 导入Junit4的jar包 单元测试工具

示例

hibernate配置文档

创建hibernate配置文档,文档内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!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="connection.username">root</property>
            <property name="connection.password"></property>
            <property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate?useUnicode=true&amp;characterEncoding=UTF-8</property>
            <!-- 方言 -->
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

            <property name="show_sql">true</property>
            <property name="format_sql">true</property>
            <property name="hbm2ddl.auto">create</property>
    </session-factory>
</hibernate-configuration>

创建持久化类

原则:

  1. 公有的类
  2. 提供公有的不带参数的默认的构造方法
  3. 属性私有
  4. 属性setter/getter封装

创建Students类,如下

package com.imooc.wz
import java.util.Date;

//学生类
public class Students {

//1. 公有的类
//2. 提供公有的不带参数的默认的构造方法
//3. 属性私有
//4. 属性setter/getter封装

private int sid;//学号
private String sname;//姓名
private String gender;//性别
private Date birthday;//出生日期
private String address;//地址

public Students() {

}

public Students(int sid, String sname, String gender, Date birthday, String address) {
this.sid = sid;
this.sname = sname;
this.gender = gender;
this.birthday = birthday;
this.address = address;
}

public int getSid() {
return sid;
}

public void setSid(int sid) {
this.sid = sid;
}

public String getSname() {
return sname;
}

public void setSname(String sname) {
this.sname = sname;
}

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}


@Override
public String toString() {
return "Students [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday
+ ", address=" + address + "]";
}




}

创建对象-关系映射文件和数据库

创建Hibernate XML Mapping file(hbm.xml)
创建的Students.hbm.xml文件为:

<?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-4-12 8:57:05 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.imooc.wz.Students" table="STUDENTS">
        <id name="sid" type="int">
            <column name="SID" />
            <generator class="assigned" />
        </id>
        <property name="sname" type="java.lang.String">
            <column name="SNAME" />
        </property>
        <property name="gender" type="java.lang.String">
            <column name="GENDER" />
        </property>
        <property name="birthday" type="java.util.Date">
            <column name="BIRTHDAY" />
        </property>
        <property name="address" type="java.lang.String">
            <column name="ADDRESS" />
        </property>
    </class>
</hibernate-mapping>

在文档生成之后,还需要加到hibernate.cfg.xml配置文档之中:
hibernate.cfg.xml最终结果为:

<?xml version="1.0" encoding="UTF-8"?>
<!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="connection.username">root</property>
            <property name="connection.password"></property>
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate?useUnicode=true&amp;characterEncoding=UTF-8</property>
            <!-- 方言 -->
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

            <property name="show_sql">true</property>
            <property name="format_sql">true</property>
            <property name="hbm2ddl.auto">create</property>

            <mapping resource="com/imooc/wz/Students.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

使用Junit进行测试

@Test - 测试方法
@Before - 初始化方法
@After - 释放资源

通过Hibernate API编写访问数据库的代码
Hibernate入门_第1张图片

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.imooc.wz.Students;

//测试类
public class StudentsTest {

    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;//事务对象


    @Before
    public void init()
    {
        //创建配置对象
        Configuration config = new Configuration().configure();
        //创建服务注册对象
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //创建会话工厂对象
        sessionFactory = config.buildSessionFactory(serviceRegistry);
        //会话对象
        session = sessionFactory.openSession();
        //开启事务
        transaction = session.beginTransaction();
    }

    @Test
    public void testSaveStudents()
    {
        //生成学生对象
        Students s = new Students(1, "美女", "女", new Date(), "武当山");
        session.save(s);//保存对象进入数据库
    }

    @After
    public void destory()
    {
        transaction.commit();//提交事务
        session.close();//关闭会话
        sessionFactory.close();//关闭会话工厂
    }

}

最后查看结果,是否在数据库中插入数据。

你可能感兴趣的:(Hibernate)