hibernate - spring-data-jpa to insert using @Query & @Modifying without using nativeQuery or save() or saveAndFlush() -
i have seen these links
- how use jpa query insert data db? uses nativequery=true
- how insert db in spring-data? suggests using built-in save method (there saveandfulsh() method)
my example below:
person simple entity w/ 3 fields "long id, string name, integer age", and, maps corresponding person table w/ 3 columns per above)
@repository public interface dualrepository extends jparepository<dual,long> { @modifying @query(? - goes here - ?) public int modifyingqueryinsertperson(@param("id")long id, @param("name")string name, @param("age")integer age); }
is there way insert using @query & @modifying (i.e. without using native sql query & nativequery=true, or, save(), or, saveandflush() ?
after trying several things, there way depends on db you're using.
below worked me in oracle & 1 row inserted table (using dual table because can use "from dual" after "select"):
@repository public interface dualrepository extends jparepository<dual,long> { @modifying @query("insert person (id,name,age) select :id,:name,:age dual") public int modifyingqueryinsertperson(@param("id")long id, @param("name")string name, @param("age")integer age); }
in ms sqlserver it's possible have "select" without "from clause", "select 10,'name10',100" works, below should work ms sqlserver (but have not tested this)
@repository public interface personrepository extends jparepository<person,long> { @modifying @query("insert person (id,name,age) select :id,:name,:age") public int modifyingqueryinsertperson(@param("id")long id, @param("name")string name, @param("age")integer age); }
i've not tried w/ other databases. here's link shows (at end) db's support select stmts without clause : http://modern-sql.com/use-case/select-without-from
Comments
Post a Comment