spring-data-jpa 使用 @Query & @Modifying 插入而不使用 nativeQuery 或 save() 或 saveAndFlush()

6 hibernate insert spring-data spring-data-jpa

我看过这些链接

我的例子如下:

Person 是一个简单的实体,有 3 个字段“长 ID、字符串名称、整数年龄”,并且映射到相应的 Person 表,上面有 3 列)

@Repository
public interface DualRepository extends JpaRepository<Dual,Long> {
    @Modifying
    @Query(? - what goes here - ?)
    public int modifyingQueryInsertPerson(@Param("id")Long id, @Param("name")String name, @Param("age")Integer age);
}
Run Code Online (Sandbox Code Playgroud)

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

小智 6

在尝试了几件事之后,有一种方法可以做到这一点,但这取决于您使用的数据库。

下面在 Oracle 中为我工作,将 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);
}
Run Code Online (Sandbox Code Playgroud)

在 MS SqlServer 中可能有一个没有“from 子句”的“select”,所以“select 10,'name10',100”可以工作,所以下面的应该适用于 MS Sqlserver(但没有测试过)

@Repository
public interface PersonRepository extends JpaRepository<Person,Long> {
    @Modifying
    @Query("insert into Person (id,name,age) select :id,:name,:age")
    public int modifyingQueryInsertPerson(@Param("id")Long id, @Param("name")String name, @Param("age")Integer age);
}
Run Code Online (Sandbox Code Playgroud)

我还没有尝试过使用任何其他数据库。这是一个链接,它显示(最后)哪个数据库支持 select stmts 没有 from 子句:http ://modern-sql.com/use-case/select-without-from


San*_*rur 6

而是传递所有参数,您可以传递java对象,如下所示

 @Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "insert into [xx_schema].[shipment_p] (gpn,qty,hscode,country_of_origin,created_date_time,shipment_id) "
            + "VALUES (:#{#sp.gpn},:#{#sp.qty},  :#{#sp.hscode} ,:#{#sp.countryOfOrigin}, :#{#sp.createdDateTime}, :#{#sp.id} )", nativeQuery = true)
    public void saveShipmentPRoducts(@Param("sp") ShipmentProducts sp);

Run Code Online (Sandbox Code Playgroud)