Application + Hibernate + Mysql(非Web)

Springboot + Hibernate + Mysql:Spring Data JPA + Hibernate + Mysql-CSDN博客

使用 Maven 构建 Hibernate 项目

创建User表

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `name` varchar(50) NOT NULL COMMENT '名称',
  `password` varchar(50) NOT NULL COMMENT '密码',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

引入依赖项

分别引入 Hibernate、MySQL 数据库驱动、单元测试 Junit4

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.14.Final</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.18</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
        </resource>
    </resources>
</build>

Hibernate 配置文件

在 resource 目录下创建 hibernate.cfg.xml 配置文件:

<hibernate-configuration>
    <session-factory>
        <!-- 配置数据源、连接池等相关信息 -->
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_demo</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- Hibernate 方言 -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 打印 SQL 语句-->
        <property name="show_sql">true</property>
        <!-- 格式化 SQL 语句-->
        <property name="format_sql">true</property>
        <!-- 映射文件所在位置 -->
        <mapping resource="User.hbm.xml" />
    </session-factory>
</hibernate-configuration>

创建映射文件User.hbm.xml

<hibernate-mapping>
    <class name="org.example.entity.User" table="user">
        <!-- 主键 -->
        <id name="id" column="id" type="java.lang.Integer">
            <generator class="native"/>
        </id>
        <property name="name" column="name" type="string" not-null="true" length="50"/>
        <property name="password" column="password" not-null="true" length="50"/>
    </class>
</hibernate-mapping>

实体类

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class User {
    private Integer id;
    private String name;
    private String password;
}

Hibernate 工具类

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

public class HibernateUtil {

    /**
     * 一个 ThreadLocal 变量,用于存储线程局部变量 Session。
     * ThreadLocal 提供了线程局部变量的机制,保证每个线程都有自己的 Session 实例。
     */
    private static final ThreadLocal<Session> THREAD_LOCAL = new ThreadLocal<>();

    private static SessionFactory sessionFactory;

    static {
        try{
            // 读取 hibernate.cfg.xml 配置文件并创建 SessionFactory
            Configuration configure = new Configuration().configure();
            sessionFactory = configure.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("Hibernate 创建会话工厂失败!");
            e.printStackTrace();
        }
    }

    /**
     * 获取 Session 对象
     */
    public static Session getSession() {
        Session session = THREAD_LOCAL.get();
        if (session == null || session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession() : null;
            THREAD_LOCAL.set(session);
        }
        return session;
    }

    /**
     * 重新创建会话工厂
     */
    private static void rebuildSessionFactory() {
        try{
            // 读取 hibernate.cfg.xml 配置文件并创建 SessionFactory
            Configuration configure = new Configuration().configure();
            sessionFactory = configure.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("Hibernate 创建会话工厂失败!");
            e.printStackTrace();
        }
    }

    /**
     * 返回唯一的会话工厂对象
     */
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * 关闭 Session 对象
     */
    public static void closeSession() {
        Session session = THREAD_LOCAL.get();
        THREAD_LOCAL.remove();
        if (session != null) {
            session.close();
        }
    }

}

测试

import org.example.entity.User;
import org.example.util.HibernateUtil;
import org.hibernate.Session;
import org.junit.Test;

public class HibernateTest {

    @Test
    public void test() {
        // 获取 Session 对象
        Session session = HibernateUtil.getSession();
        User user = new User();
        user.setName("Jiang");
        user.setPassword("123456");
        try {
            // 开启事务,即使是执行一次数据库操作,也是事务
            session.beginTransaction();
            // 执行插入操作
            session.save(user);
            // 提交事务
            session.getTransaction().commit();
        } catch (Exception e) {
            // 发生异常,则回滚事务
            session.getTransaction().rollback();
            System.out.println("插入User数据失败!");
            e.printStackTrace();
        } finally{
            // 关闭 Session 对象
            HibernateUtil.closeSession();
        }
    }
}

github代码:https://github.com/JJJ2018/Hibernate_Mysql_Application

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值