Reputation: 173
my code is
`@Id
@GenericGenerator(name="generator", strategy="increment")
@GeneratedValue(generator="generator")
@Column(name = "PM_ID", nullable = false, length=12)
private long pmId;`
In above id is genarate by max id +1 from database but I want to generate this pmid column from database function and want to pass value to that function. my function name is generateID(2,3)
So please tell me how to do this..
Upvotes: 6
Views: 3194
Reputation: 1097
You can use a custom ID generator to call your stored procedure.
Define your @Id
as this to point to your custom generator :
@Id
@GenericGenerator(name="MyCustomGenerator", strategy="org.mytest.entity.CustomIdGenerator" )
@GeneratedValue(generator="MyCustomGenerator" )
@Column(name = "PM_ID", nullable = false, length=12)
private long pmId;
private Integer field1;
private Integer field2;
.... your getters and setters ....
And create your custom generator implementing IdentifierGenerator
and passing properties of your Entity as stored proc parameters:
public class CustomIdGenerator implements IdentifierGenerator {
private static final String QUERY_CALL_STORE_PROC = "call generateId(?,?,?)";
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
Long result = null;
try {
Connection connection = session.connection();
CallableStatement callableStmt = connection. prepareCall(QUERY_CALL_STORE_PROC);
callableStmt.registerOutParameter(1, java.sql.Types.BIGINT);
callableStmt.setInt(2, ((MyObject) object).getField1());
callableStmt.setInt(3, ((MyObject) object).getField2());
callableStmt.executeQuery();
// get result from out parameter #1
result = callableStmt.getLong(1);
connection.close();
} catch (SQLException sqlException) {
throw new HibernateException(sqlException);
}
return result;
}
}
Upvotes: 7