简体   繁体   中英

Hibernate generate ID from database function

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..

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;
  }
} 

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