框架:hibernate+mysql入门使用

一、简介

     Hibernate是一个开放源代码的对象关系映射框架。

二、入门使用

     1、添加依赖

          a、使用maven管理依赖,以我本次使用的版本为例

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.5.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
</dependencies>
View Code

    b、也可以使用gradle管理依赖

dependencies {

    testCompile 'junit:junit:4.12'
    compile 'org.hibernate:hibernate-core:4.3.5.Final'
    compile 'mysql:mysql-connector-java:5.1.38'

    compile 'org.slf4j:slf4j-api:1.7.21'
    compile 'org.slf4j:slf4j-log4j12:1.7.21'
    compile 'log4j:log4j:1.2.17'
}
View Code

              c、也可以去官网下载,官网地址:http://hibernate.org/

     2、初始化数据库,Hibernate可以根据配置自动生成表结构

-- 创建数据库
CREATE  DATABASE  moy_hibernate;
View Code

     4、新建实体类TestEntity

package com.moy.hibernate4.entity;

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

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/25  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
@Entity
@Table(name = "t_test")
public class TestEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;
    private Date createTime;
    private Date modifyTime;

    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 Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getModifyTime() {
        return modifyTime;
    }

    public void setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
    }

    @Override
    public String toString() {
        return "TestEntity{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", createTime=" + createTime +
                ", modifyTime=" + modifyTime +
                '}';
    }
}
View Code

     5、新建Hibernate配置信息文件hibernate.cfg.xml,和新建日志配置文件(方便定位问题)log4j.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.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 -->
        <property name="connection.url">jdbc:mysql://localhost:3306/moy_hibernate</property>
        <!-- 指定连接数据库的用户名 -->
        <property name="connection.username">root</property>
        <!-- 指定连接数据库的密码 -->
        <property name="connection.password">123</property>
        <!-- 指定数据库方言 -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <!-- 根据需要自动创建数据表 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- 显示Hibernate持久化操作所生成的SQL -->
        <property name="show_sql">true</property>
        <!-- 将SQL脚本进行格式化后再输出 -->
        <!--<property name="hibernate.format_sql">true</property>-->
        <!-- 罗列所有持久化类的类名 -->
        <mapping class="com.moy.hibernate4.entity.TestEntity"></mapping>
    </session-factory>
</hibernate-configuration>
View Code
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %-5p %-5c{3}\:%L %x %n-> %m%n"/>
        </layout>
    </appender>
    <root>
        <priority value="DEBUG"/>
        <appender-ref ref="console"/>
    </root>
</log4j:configuration> 
View Code

     6、为了方便测试,编写一个获取Session的工具类Hibernate4Utils

package com.moy.hibernate4.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import java.util.Objects;

public abstract class Hibernate4Utils {

    static {
        try {
            Configuration conf = new Configuration().configure();
            ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
            sessionFactory = conf.buildSessionFactory(registry);
        } catch (Throwable e) {
            throw e;
        }
    }

    public static final SessionFactory sessionFactory;

    public static final ThreadLocal<Session> sessionThread = new ThreadLocal<>();

    /**
     * 获取当前线程安全Session
     */
    public static Session getCurrentSession() {
        Session session = sessionThread.get();
        if (Objects.isNull(session)) {
            session = sessionFactory.openSession();
            sessionThread.set(session);
        }
        return session;
    }

    /**
     * 关闭Session
     */
    public static void closeCurrentSession() {
        Session session = sessionThread.get();
        if (Objects.nonNull(session)) {
            session.close();
        }
        sessionThread.set(null);
    }
}
View Code

     7、新建测试类TestEntityTest测试

package com.moy.hibernate4.entity;

import com.moy.hibernate4.util.Hibernate4Utils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Project:moy-gradle-project  <br/>
 * Description:  <br/>
 * Date:2017/12/26  <br/>
 * Email:moy25@foxmail.com  <br/>
 *
 * @author YeXiangYang
 */
public class TestEntityTest {
    Session session;
    Transaction transaction;

    @Before
    public void before() {
        session = Hibernate4Utils.getCurrentSession();
        transaction = session.beginTransaction();
    }

    @After
    public void after() {
        transaction.commit();
        Hibernate4Utils.closeCurrentSession();
    }

    @Test
    public void insert() {
        TestEntity entity = getTestEntity();
        System.out.println("TestEntityTest#save()结果:" + session.save(entity));
    }

    private TestEntity getTestEntity() {
        TestEntity entity = new TestEntity();
        entity.setCreateTime(new Date());
        entity.setModifyTime(new Date());
        entity.setName("我是测试");
        return entity;
    }

    @Test
    public void get() {
        TestEntity entity = getTestEntity();
        Serializable id = session.save(entity);
        System.out.println("TestEntityTest#get()结果:" + session.get(TestEntity.class, id));
    }

    @Test
    public void count() {

        Query query = session.createQuery("SELECT COUNT(*) FROM TestEntity");
        List list = query.list();

        if (Objects.nonNull(list) && 1 == list.size()) {
            System.out.println("TestEntityTest#count()结果:" + list.get(0));
        }
    }


    @Test
    public void list() {
        Query query = session.createQuery("from TestEntity");
        List list = query.list();

        if (Objects.nonNull(list)) {
            System.out.println("TestEntityTest#list结果:" + Arrays.toString(list.toArray()));
        }
    }

    @Test
    public void update() {
        TestEntity entity = getTestEntity();
        Serializable id = session.save(entity);
        entity = (TestEntity) session.get(TestEntity.class, id);
        entity.setName("我是被修改的测试");
        entity.setModifyTime(new Date());
        session.update(entity);
    }

    @Test
    public void delete() {
        TestEntity entity = getTestEntity();
        Serializable id = session.save(entity);
        entity = (TestEntity) session.get(TestEntity.class, id);
        session.delete(entity);
    }
}
View Code

 

 

yexiangyang

moyyexy@gmail.com


 

posted @ 2018-02-25 21:37  墨阳  阅读(2110)  评论(0编辑  收藏  举报