最近在使用hibernate+spring的时候,在update时,遇到一些问题,这里记录一下。
一般常用的DML:Data Manipulation Language 数据操纵语言,对表的数据进行操作,(insert、update、delete )语句 和 DCL:Data Control Language 数据库控制语言(创建用户、删除用户、授权、取消授权)语句 和 DDL:Data Definition Language 数据库定义语言,对数据库内部的对象进行创建、删除、修改的操语句,均是使用MySQL提供的公共接口mysql_execute_command,来执行相应的SQL语句。
在Spring配置文件中,添加如下配置,这个配置的作用,就是管理当前的session,针对一些需要事务支持的操作,自动提交。
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"
xmlns:tx="http://www.springframework.org/schema/tx"
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<task:annotation-driven/>
使用时,只需要在方法上增加@Transactional注解
@Transactional
public void test() {
try {
//获取当前session
Session session = sessionFactory.getCurrentSession();
ServiceLogEntity serviceLogEntity = (ServiceLogEntity) session
.createNativeQuery("select * from contrarian_service_log limit 1")
.addEntity(ServiceLogEntity.class).uniqueResult();
serviceLogEntity.setName("测试测试2");
session.update(serviceLogEntity);
} catch (Exception e) {
e.printStackTrace();
}
}