一尘不染

如何在JPA中生成自定义ID

spring-boot

我想在JPA中生成自定义ID,它必须是表的主键。有很多例子可以创建自定义ID使用像Hibernate这样 我想相同的实现,但在JPA.The
ID必须是字母数字像STAND0001

谢谢。


阅读 1196

收藏
2020-05-30

共1个答案

一尘不染

您可以这样使用GenericGenerator

 @Entity
public class Client {

    @Id
    @GenericGenerator(name = "client_id", strategy = "com.eframe.model.generator.ClientIdGenerator")
    @GeneratedValue(generator = "client_id")  
    @Column(name="client_id")
    private String clientId;
}

和自定义生成器类(将在ID之前添加前缀,您可以根据自己的喜好进行设置):

public class ClientIdGenerator implements IdentifierGenerator {

@Override
public Serializable generate(SessionImplementor session, Object object)
        throws HibernateException {

    String prefix = "cli";
    Connection connection = session.connection();

    try {
        Statement statement=connection.createStatement();

        ResultSet rs=statement.executeQuery("select count(client_id) as Id from Client");

        if(rs.next())
        {
            int id=rs.getInt(1)+101;
            String generatedId = prefix + new Integer(id).toString();
            return generatedId;
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}
}
2020-05-30