第一个hibernate应用程序

  • 搭建hibernate环境
    • 将所需jar包单独打包新建一个library之后添加到项目中
    • 使用的数据库为Oracle,需要Oracle数据库驱动的jar文件。如果使用别的数据库,只需选择对象的驱动文件
    • 网盘链接:hibernate需要的jar包
  • 创建实体类
    • 源码
package com.dhee.entity;

/**
 * person实体类
 * 
 * @author Inspiron
 *
 */
public class Person implements java.io.Serializable {

    private static final long serialVersionUID = 1045122557721301152L;
    private Integer id;
    private String name;
    private Integer age;
    private String title;

    public Person() {

    }

    public Person(Integer id, String name, Integer age, String title) {
        this.title = title;
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

}
  • 创建工具类
    • 获得SessionFactory对象
package com.dhee.utils;

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

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    /**
     * 获得sessionFactory对象
     * 
     * @return返回sessionFactory对象
     */
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}
  • 必要的配置文件
    • 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>

        <!-- Database connection settings -->
        <!-- Oracle数据库加载驱动 -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <!-- 连接数据库url -->
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
        <!-- 数据库名 -->
        <property name="connection.username">system</property>
        <!-- 连接数据库的密码 -->
        <property name="connection.password">yuanbao</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <!-- 连接数据库对应的方言 -->
        <!-- Oracle 11g         org.hibernate.dialect.Oracle10gDialect -->
        <!-- MySQL5     org.hibernate.dialect.MySQL5Dialect -->
        <!-- Microsoft SQL Server 2008          org.hibernate.dialect.SQLServer2008Dialect -->
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- 控制台是否打印sql语句 -->
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <!-- 设置实体类的url,如果使用xml配置文件:使用resource="指向xml配置文件" -->
        <!-- 例如:<mapping resource="com/dhee/entity/Person.hbm.xml"/> -->
        <!-- 如果使用annotation注释:使用class="实体类的路径" -->
        <!--  <mapping class="com.dhee.entity.Preson"/> -->
        <mapping resource="com/dhee/entity/Person.hbm.xml"/>

    </session-factory>

</hibernate-configuration
>
  • 对应的实体类映射配置文件
    • Person.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="com.dhee.entity">
    <class name="Person" table="PERSON">
        <!-- 对应数据表中的主键 -->
        <id name="id">
            <generator class="native"/>
        </id>
        <!-- 如果实体类的成员变量和数据库字段名对应一致的话,可以只写name -->
        <property name="name"/>
        <property name="age"/>
        <property name="title"/>
    </class>
</hibernate-mapping>
  • 创建数据表PERSON
CREATE TABLE PERSON(
    ID NUMBER(4) PRIMARY KEY,
    NAME VARCHAR2(20 CHAR),
    AGE NUMBER(4),
    TITLE VARCHAR2(20 CHAR);
  • 创建测试代码
package com.dhee.test;

import org.hibernate.classic.Session;

import com.dhee.entity.Person;
import com.dhee.utils.HibernateUtil;

public class PersonTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Person p = new Person();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();

        p.setId(1);
        p.setName("tom");
        p.setAge(20);
        p.setTitle("student");

        session.beginTransaction();
        session.save(p);
        session.getTransaction().commit();

    }

}
  • 执行PersonTest类,控制台打印出insert语句,数据添加成功

  • 如果对于实体类不使用xml配置文件,可以使用注解,修改hibernate.cfg.xml文件中mapping标签的class

package com.dhee.entity;

import javax.persistence.Entity;
import javax.persistence.Id;

/**
 * person实体类
 * 
 * @author Inspiron
 *
 */
@Entity
public class Person implements java.io.Serializable {

    private static final long serialVersionUID = 1045122557721301152L;
    private Integer id;
    private String name;
    private Integer age;
    private String title;

    public Person() {

    }

    public Person(Integer id, String name, Integer age, String title) {
        this.title = title;
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Id //注解表示主键,主键注解写在getXX上面
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

}
  • END
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值