简体   繁体   中英

Get Entity ID after executing Native insert query + Spring JPA

I am using a Native query in my JPA Repository to run INSERT query - because, I couldn't run a few queries through JPA.

String INSERT_USER_IN_TO_DATABASE = "INSERT INTO USER_MASTER " +
            "(" +
            "MOBILE_X,USER_TYPE,COUNTRYCODE,USER_N,USER_LAST_N,GENDER,DOB) " +
            "VALUES ( " +
            "EncryptByKey(Key_GUID(convert(varchar,?1)), ?2)," +
            "1,+91,?3,?4,?5,?6" +
            ")";

    @Query(value = INSERT_USER_IN_TO_DATABASE, nativeQuery = true)
    @Modifying
    UserMasterEntity saveNewUser(String encryptionKey,
                                 String phoneNumber,
                                 String name,
                                 String lastName,
                                 String gender,
                                 String dob);

My intention is to execute the INSERT statement and get me the userMaster entity. But I get the below exception

Caused by: java.lang.IllegalArgumentException: Modifying queries can only use void or int/Integer as return type! Offending method: public abstract com.officeride.fileprocess.job.bulkuser.UserMasterEntity com.officeride.fileprocess.job.bulkuser.UserMasterRepository.saveNewUser(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String)

I used @ColumnTransformer stuff too in my entity and nothing is working out for me.

How to tackle this?

You cannot make the INSERT INTO statement return anything. Depending on your database's support, on that end you could execute multiple statements, eg, INSERT INTO...; SELECT... INSERT INTO...; SELECT... , but Spring Data JDBC does not support this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM