【问题标题】:"insert ignore" or "on duplicate key update" using @Query & @Modifying without using nativeQuery or save() or saveAndFlush() JPA Hibernate“插入忽略”或“重复键更新”使用 @Query 和 @Modifying 而不使用 nativeQuery 或 save() 或 saveAndFlush() JPA Hibernate
【发布时间】:2021-09-14 06:58:27
【问题描述】:

我的例子如下:

Person 是一个简单的实体,有 3 个字段“Long id, String name, Integer age”,并且映射到对应的 Person 表,上面每列 3 列)

@Repository
public interface PersonRepository extends JpaRepository<Person,Long> {

    @Modifying
    @Query(? - what goes here - ?)
    public int modifyingQueryInsertPerson(@Param("id")Long id, @Param("name")String name, @Param("age")Integer age);
}

有没有办法只使用 @Query 和 @Modifying 进行插入(即不使用原生 SQL 查询 & nativeQuery=true,或者,save(),或者,saveAndFlush()?

重要>> 此外,当记录已存在于表中时,我希望能够更新记录,例如“插入忽略”或“重复键更新”?

请帮忙。

【问题讨论】:

  • 这仅适用于本机 sql,因为 JPQL 中不存在该构造(还没有?)。所以你需要一个原生的 SQL 语句。
  • 但是使用本机查询会失去迁移到不同数据库的灵活性,那么如果我必须使用本机查询,那么使用 JPA 的意义何在。
  • 因为 JPA / JPQL 根本无法实现您想要实现的目标。因为目前还没有执行 UPSERT/MERGE 语句的共同点。因此 JPA 不支持它,您必须编写它。更改数据库是一种谬论,除非您编写的产品需要在多个数据库上运行,否则需要的不仅仅是重写一些查询。

标签: java spring hibernate jpa insert-update


【解决方案1】:

我找到了这个解决方案,但它不适用于“插入忽略”或“重复密钥更新”:

@Repository
public interface DualRepository extends JpaRepository<Dual,Long> {
    @Modifying
    @Query("insert into Person (id,name,age) select :id,:name,:age from Dual")
    public int modifyingQueryInsertPerson(@Param("id")Long id, @Param("name")String name, @Param("age")Integer age);
}

【讨论】:

    猜你喜欢
    • 2018-01-26
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    • 2011-11-13
    • 2018-10-07
    • 2016-06-15
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多