createNativeQuery方法,Hiberbate的事务不生效问题解决

问题描述

在使用Hibernate作为持久层框架时,我们有时会使用 createNativeQuery 方法编写原生SQL来更新数据:

public boolean updateData(UUID newAddCardId){
String hql = "update fdw_detail set IS_DELETED = 2 where INV_DET_ID = :bookId";
        try {
            template.execute(session -> session.createNativeQuery(hql)
                    .setParameter("bookId", bookId)
                    .executeUpdate()
            );
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

但是在使用过程中可能会遇到事务不生效,更新数据不提交的问题!

问题分析

我这边是这样使用的 :

Service 层:

@Service
public class HService {
@Transactional
    public String updateTest(UUID newAddCardId) {

    //调用真正更新数据库的方法
    updateData(newAddCardId);

}


public boolean updateData(UU
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
非常抱歉之前的回答有误。 如果在代码中使用 Hibernate 创建一个新的自定义序列,你可以使用 Hibernate 的 `SchemaExport` 类来执行 DDL 语句来创建序列。 以下是示例代码: ```java import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; public class CreateCustomSequenceExample { public static void main(String[] args) { StandardServiceRegistry registry = null; try { // 创建 Hibernate 配置对象 org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration().configure(); // 根据配置创建标准服务注册对象 registry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); // 使用元数据构建器创建元数据源 MetadataSources sources = new MetadataSources(registry); Metadata metadata = sources.buildMetadata(); // 创建 SchemaExport 对象,并指定输出类型为脚本文件 SchemaExport schemaExport = new SchemaExport(); schemaExport.setDelimiter(";"); schemaExport.setOutputFile("create_sequence_script.sql"); schemaExport.createOnly(TargetType.SCRIPT, metadata); // 执行脚本文件 schemaExport.execute(TargetType.SCRIPT, SchemaExport.Action.CREATE, metadata); } catch (Exception e) { e.printStackTrace(); } finally { if (registry != null) { StandardServiceRegistryBuilder.destroy(registry); } } } } ``` 在这个例子中,我们使用 Hibernate 的 `SchemaExport` 类来执行 DDL 语句来创建序列。通过指定输出类型为脚本文件,可以将生成的 SQL 脚本保存到文件中。 执行以上代码后,会在项目根目录下生成一个名为 `create_sequence_script.sql` 的 SQL 脚本文件,其中包含了创建序列的语句。你可以根据需要执行该脚本文件来创建自定义序列。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ThatMonth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值