Hibernate学习笔记1

来源:互联网 发布:国际金融网络课程答案 编辑:程序博客网 时间:2024/05/02 01:24

一、导入jar包的两种方式

1、常规导入:项目右键 ----> Build Path -----> Add External Archives(添加外部jar包)

2、作为用户自定义libraries保存

  • window  ---->  preferences ----->  Build Path ----->  Use Libraries(用户自定义的Libraries,此时Libraries里面可以包括很多jar包。例如我们引入struts、hibernate的时候往往引入的jar包不止一个,此时就可以使用Libraries进行归类)  ----->  New  ------->  新建(eg:hibernate) ------>   Add JARs( 添加需要引入的jar包)
  • 项目右键 ----> Build Path -----> Add Libraries ----> User Libraries ----->  添加新建的Libraries(eg:hibernate)

二、Hibernate 4jar包的引入和配置

  1. Hibernate4需要引入的jar包:找到lib目录下面的requried文件夹,将文件夹中的内容一起引入。同时也需要导入数据库jar包。
  2. hibernate4实例
  • 先建立一个与数据库对应的Java实体类对象(eg:UserModel)

package com.h4.hello;

public class UserModel {

    public UserModel() {
        super();
    }

    private String uuid;
    private String userId;
    private String name;
    private int age;

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}

  • 数据库建表,要与UserModel中的字段对应,假设建一个表tbl_user:
  • 编写配置文件XX.cfg.xml(一般使用hibernate.cfg.xml)存放在classes根目录下面,开发的时候可以直接放在src下面,配置的时候可以参考文档,格式如下:

<?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>
        <!-- 数据库驱动名称,此处使用的是mysql -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 数据库链接地址 -->
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <!-- 数据库用户名称-->
        <property name="connection.username">root</property>
        <!-- 数据库密码 -->
        <property name="connection.password">123456</property>
        <!-- 设置数据库连接池默认个数 -->
        <property name="connection.pool_size">2</property>
        <!-- 设置数据库SQL语言类型 -->
        <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
        <!-- 设置是否显示SQL语句-->
        <property name="show_sql">true</property>
        <!-- 设置hibernate的映射文件 -->
        <mapping resource="com/h4/hello/UserModel.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

  • 配置XXX.hbm.xml(此处为UserModel.hbm.xml)。此映射文件可以理解成是持久化的类与数据表之间的对应关系。此时有几点需要注意:第一、与被描述的类同名(例如描述UserModel实体类,则使用UserModel.hbm.xml);第二,存放位置与所属类存放在同一个文件夹。实例如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
'-//Hibernate/Hibernate Mapping DTD 3.0//EN'
'http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd'>
<hibernate-mapping>
    <class name="com.h4.hello.UserModel" table="tbl_user">     <!---类与表的映射,注意红色标记处为所描述类名称而不是UserModel.hbm.xm文件名称---->
        <id name="uuid" type="string" column="uuid">      <!---主键的映射,红色部分有很多种类型,此时表示用户定义---->
            <generator class="assigned"/>
        </id>

        <!---实体类的属性与db中字段的映射,name表示实体名称,column表示对应DB中字段名称---->
        <property name="userId" column="userId" type="string" not-null="false" length="32"/>
        <property name="name" column="name" type="string" not-null="false" length="20"></property>
        <property name="age" column="age" type="java.lang.Integer" not-null="false" length="10"></property>

         <!---还可以有关系(外键)的映射,此处暂时不设---->
    </class>
</hibernate-mapping>
  • 编写测试类实现测试(可参考文档),实例如下
package com.h4.hello;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SessionFactory ses = new Configuration()

                .configure()

                .buildSessionFactory(); 

   //这句话的意思是读取hibernate.cfg.xml,创建Session工厂,是线程安全的。  默认是”hibernate.cfg.xml”,不用写 来 configure(),如果文件名不是”hibernate.cfg.xml”,那么需要显示指定configure(“文件名称”)

        Session s = null;        // Session是应用程序主要使用的Hibernate接口,约相当于JDBC的 Connection+Statement/PreparedStatement的功能,是线程不安全的

        Transaction t = null;
        UserModel user = new UserModel();
        try {
            user.setAge(25);
            user.setName("pl");
            user.setUuid("2007");
            user.setUserId("1211082074");
            s = ses.openSession();
            t = s.beginTransaction();
            s.save(user);                   
            t.commit();
        } catch (Exception err) {
            t.rollback();
            err.printStackTrace();
        } finally {
            s.close();
        }
    }

}




原创粉丝点击