SSH框架 Hibernate(使用C3P0连接池)向数据库中插入数据,但是数据不显示

!!!困扰了两个小时

发现了向数据库中插入数据,结果idea并没有报错,但是数据库中不显示数据,原因是数据库中的数据并没有设置自动提交。!!!

需要在hibernate.cfg.xml中加入一条代码

<!--自动提交事务-->
<property name="connection.autocommit">true</property>

下边为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>
        <!-- 连接数据库的基本参数 -->
	<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
	<property name="hibernate.connection.url">jdbc:mysql:///hibernate?characterEncoding=utf-8&amp;serverTimezone=UTC&amp;useSSL=false</property>
	<property name="hibernate.connection.username">root</property>
	<property name="hibernate.connection.password">123456</property>

	<!-- 配置Hibernate的方言   MySQL5Dialect若不写中间的那个5,可能会报表找不到的错误   -->
	<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
	<!-- 打印SQL -->
	<property name="hibernate.show_sql">true</property>
	<!-- 格式化SQL -->
	<property name="hibernate.format_sql">true</property>
	<!--自动提交事务-->
	<property name="connection.autocommit">true</property>
	<!-- 自动创建表 -->
	<property name="hibernate.hbm2ddl.auto">update</property>

	<!--    C3P0   -->
	<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
	<!--在连接池中可用的数据库连接的最少数目 -->
	<property name="c3p0.min_size">5</property>
	<!--在连接池中所有数据库连接的最大数目  -->
	<property name="c3p0.max_size">20</property>
	<!--设定数据库连接的过期时间,以秒为单位,
     	 如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
	<property name="c3p0.timeout">120</property>
	<!--3000秒检查所有连接池中的空闲连接 以秒为单位-->
	<property name="c3p0.idle_test_period">3000</property>
        <!--加载映射文件-->
      <mapping resource="com/myxq/domain/Customer.hbm.xml"/>
   </session-factory>
</hibernate-configuration>

C3P0不会自动提交事务,所以在使用Hibernate进行数据库数据更新时,需要开启事务,并提交事务。

@Test
public void Test2(){
   	 //获取session
   	 Session session = HibernateUtil.openSession();
	//开启事务
	Transaction transaction = session.beginTransaction();

	//更新操作
	Customer customer = new Customer();
	customer.setCust_id(29L);
	customer.setCust_name("myxq_update");
	session.update(customer);

	//提交事务
	transaction.commit();

	//释放资源
	session.close();
发布了21 篇原创文章 · 获赞 7 · 访问量 351

猜你喜欢

转载自blog.csdn.net/qq_45260619/article/details/104078001