JUnit 测试hibernate添加数据控制台有insert语句,但数据库无数据

JUnit 做hibernate项目单元测试的时候,发现控制台明明打印了insert语句的日志就是没有数据

这是hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.gyf.hibernate.domain.User" table="tb5">
<id name="uid" column="id">
<generator class="native"></generator>
</id>
<property name="username"></property>
<property name="password"></property>
</class>
</hibernate-mapping>

这是hibernate.cfg.xml
<!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>
        <!-- 1、配置数据库连接的4个参数 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///tb3</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>

        <!--  是否显示sql语句 -->
        <property name="show_sql">true</property>
        <!--  是否格式化sql语句 -->
        <property name="format_sql">true</property>
<!--  是否自动提交事务 -->
        <property name="hibernate.connection.autocommit">true</property>

        <!-- 2、配置JavaBean与表的映射文件 -->
        <mapping resource="com/gyf/hibernate/domain/User.hbm.xml"/>
    </session-factory>

</hibernate-configuration>
package com.gyf.hibernate.test;

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

import com.gyf.hibernate.domain.User;

public class Lesson02 {
    @Test
    public void test1(){
Configuration cfg = new Configuration().configure();

        //2.创建会话工厂
        SessionFactory factory = cfg.buildSessionFactory();

        //3.创建会话
        Session session = factory.openSession();
        //开启事务
        Transaction trans = session.beginTransaction();

        //保存
        User user = new User();
        user.setUsername("gyf");
        user.setPassword("123");
        session.save(user);

        //提交事务
        trans.commit();
        //4.关闭会话
        session.close();
        //5.关闭工厂,释放资源
        factory.close();

    }
}

https://blog.csdn.net/qq_33168577/article/details/80066846

https://blog.csdn.net/Amo_lt/article/details/79407149

使用junit测试插入,测试显示成功,但是数据并没有保存到数据库。是因为在junit下,插入数据会自动回滚,所以测试显示成功但实际上不能插入。若要插入到数据库,只需在测试方法上添加@Rollback(false)注解即可。