1.Hibernate之入门

1. 关于Hibernate

对象关系映射(ORM):Hibernate ORM,其作用就是去映射对象和关系型数据库的,以达到程序中的业务逻辑和数据访问组件相分离。

2. Hibernate和JPA的关系

JPA全称为Java Persistence API ,Java持久化API是Sun公司在Java EE 5规范中提出的Java持久化接口。JPA吸取了目前Java持久化技术的优点,旨在规范、简化Java对象的持久化工作。使用JPA持久化对象,并不是依赖于某一个ORM框架。Hibernate是JPA的一个实现。
JPA和Hibernate之间的关系,可以简单的理解为JPA是标准接口,Hibernate是实现。那么Hibernate是如何实现与JPA的这种关系的呢。

3. Hibernate入门

本次使用的Hibernate版本为5.2.5.Final

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>${hibernate.version}</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
  • 构建实体类
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;

@Entity(name = "user")
@Table(name = "t_user")
public class Subscriber implements Serializable {

    private static final long serialVersionUID = 9181139977020744196L;

    @Id
    @Column(length = 36)
    @GeneratedValue(generator = "userID")
    @GenericGenerator(name = "userID", strategy = "uuid2")
    private String userID;

    private String username;

    @Temporal(TemporalType.TIMESTAMP)
    private Date lastUpdate;

    public Subscriber() {}

    public Subscriber(String username) {
        this.username = username;
        this.lastUpdate = new Date();
    }

    @Override
    public String toString() {
        return "userID: " + this.userID + ", username: " + this.username + ", lastUpdate: " + this.lastUpdate;
    }
    /*get and set*/
}
  • Hibernate配置信息
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/persistence</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="show_sql">false</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="hibernate.current_session_context_class">thread</property>

        <mapping class="com.annwyn.persistence.database.entity.Subscriber" />
    </session-factory>
</hibernate-configuration>
  • 测试类

public class HibernateTest extends BaseTestCase {
    protected SessionFactory sessionFactory;

    @Override
    public void setUp() throws Exception {
        Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
        this.sessionFactory = configuration.buildSessionFactory();
    }

    @Override
    public void tearDown() throws Exception {
        if(this.sessionFactory != null)
            this.sessionFactory.close();
    }

    public void testInsert() throws Exception {
        Session session = this.sessionFactory.getCurrentSession();

        session.getTransaction().begin();
        Subscriber subscriber = new Subscriber("username");
        session.persist(subscriber);
        session.getTransaction().commit();
        session.close();

        session = this.sessionFactory.getCurrentSession();
        session.getTransaction().begin();
        List<Subscriber> subscribers = session.createQuery("from user", Subscriber.class).getResultList();
        ParamUtils.println(subscribers); // 打印全部Subscriber信息
        session.getTransaction().commit();
        session.close();

    }


}
  • 日志生成信息

在运行测试类时,hibernate会自动生成建表语句

create table t_user (userID varchar(36) not null, lastUpdate datetime, username varchar(255), primary key (userID))

最后测试添加与查询时hibernate发出的SQL:

2016-12-29 23:05:15 DEBUG insert into t_user (lastUpdate, username, userID) values (?, ?, ?)
2016-12-29 23:05:15 INFO  HHH000397: Using ASTQueryTranslatorFactory
2016-12-29 23:05:15 DEBUG select subscriber0_.userID as userID1_0_, subscriber0_.lastUpdate as lastUpda2_0_, subscriber0_.username as username3_0_ from t_user subscriber0_
2016-12-29 23:05:15 INFO  userID: e27276d9-070a-48d5-89e8-38144e623e59, username: username, lastUpdate: 2016-12-29 23:05:15.0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值