In a spring boot project and database SQL Server, I'm doing some inserts where I need to return the id of the record I have a Entity with few fields:
public class PackGroupEntity{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long group_id;
private String group;
private String remark;
private String description;
....
}
I simplified the insert just to ask the question.
I have an insert statement and I need to retrieve the id from the inserted record.
String query = String.format(
"insert into pack_group(group, remark, description ) " +
"values ( %s, %s, %s)", "a","b","c" );
Query q = entityManager.createNativeQuery(query );
BigInteger biid = (BigInteger) q.getSingleResult();
long id = biid.longValue();
And I get this error
com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
Based on this answer here that I can use returning id
so I tried but:
String query = String.format(
"insert into pack_group(group, remark, description ) " +
"values ( %s, %s, %s ) returning group_id;", "a","b","c" );
Query q = entityManager.createNativeQuery(query );
BigInteger biid = (BigInteger) q.getSingleResult();
long id = biid.longValue();
but it throws an error
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near 'returning'.
Can someone help me, please?