创建Hibernate的例子的步骤

创建Hibernate的例子的步骤

创建Hibernate的配置文件
创建持久化类
创建对象-关系映射文件
通过Hibernate API编写访问数据库的代码

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">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="connection.username">root</property>
        <property name="connection.password">12345678</property>
        <property name="connection.driver_class">
            com.mysql.jdbc.Driver
        </property>
        <property name="connection.url">
            jdbc:mysql:///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="./Students.hbm.xml" />
    </session-factory>

</hibernate-configuration>

connection.username是我们要连接的数据库的用户名
connection.password是密码
connection.driver_class是指定数据库的jdbc驱动,我用的是mysql的数据库,com.mysql.jdbc.Driver就是它的驱动的;类名
connection.url是访问数据库的地址,这里三个/的写法是一种简写,后面的参数是防止乱码的问题
dialect是方言,指定了我们使用MySql的具体方言+
以上是基本配置

show_sql一般设为true
format_sql也设为true
hbm2ddl是ddl语句的生成策略
这是一些常用属性

持久化类的创建

这里写图片描述
根据前边的配置文件,建立数据库hibernate,然后里边的结构如下,然后根据数据库来建立持久化类,一些注意事项也在代码中的注释给出

import java.util.Date;

//学生类
public class Students {

    // 持久化类的设计原则要遵循JavaBean的设计原则
    // 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) {
        // 为了方便生成对象,再写一个带参数的构造方法
        // 右键->Source->Generate Constructor using Fields
        // super();
        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() {
        // 方便测试,写一个toString方法
        // Source->Generate toString
        return "Students [sid=" + sid + ", sname=" + sname + ", gender="
                + gender + ", birthday=" + birthday + ", address=" + address
                + "]";
    }
}

对象-关系映射文件

然后根据前一篇文章写到的生成对象-关系映射文件的方法,来得到Students.hbm.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>
    <class name="Students" table="students" catalog="hibernate">
        <id name="sid" type="java.lang.Integer">
            <column name="SID" />
        </id>
        <!-- id这个不可以写为property,把key-property改为了property,把composite删掉 -->
        <property name="sname" type="java.lang.String">
            <column name="SNAME" length="20" />
        </property>
        <property name="gender" type="java.lang.String">
            <column name="GENDER" length="10" />
        </property>
        <property name="birthday" type="java.util.Date">
            <column name="BIRTHDAY" length="10" />
        </property>
        <property name="address" type="java.lang.String">
            <column name="ADDRESS" length="30" />
        </property>
    </class>
</hibernate-mapping>

通过Hibernate API编写访问数据库的代码

需要使用到Junit单元测试
大体的框架如下:

public class StudentsTest {

    @Before
    public void init(){

    }

    @After
    public void destory(){

    }

    @Test
    public void testSaveStudents(){

    }
}

需要有before来进行初始化操作,在执行测试方法之前执行。after用来在测试方法执行完之后释放资源。

在初始化的代码中要实现以下功能:
创建配置对象,是Configuration类的一个对象
创建服务注册对象
创建会话工厂对象,用配置对象来生成
然后使用会话工厂对象的openSession方法打开会话
然后打开事务
具体的实现步骤如下:

@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();
}

释放资源的部分应该先提交事务,然后关闭会话和关闭会话工厂

总的代码如下

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();
    }

    @After
    public void destory(){

        transaction.commit();//提交事务
        session.close();//关闭会话
        sessionFactory.close();//关闭会话工厂
    }

    @Test
    public void testSaveStudents(){
        //生产学生对象
        Students s = new Students(1,"张三丰","男",new Date(),"武当山");
        //无需编写sql语句,因为我们用的hibernate是一个ORM框架,只需要保存这个对象就好了
        session.save(s);//保存对象进入数据库
    }
}

运行测试代码可以看到已经在数据库添加了记录
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值