如何在JPA中生成自定义ID

14

我想在JPA中生成自定义ID,它必须是表的主键。有许多使用Hibernate创建自定义ID的示例,例如这个。我想要相同的实现,但在JPA中。该ID必须是字母数字混合的,例如STAND0001

谢谢。


ID必须是字符串和数字的组合。 - Amol Raje
这本身取决于Hibernate。所以你正在使用Hibernate。因此,请查阅Hibernate的文档。 - JB Nizet
你能发布一些代码吗?比如你的实体/bo/model以及你想要如何生成主键,例如数字或字符串? - Sreenath Reddy
Sreenath Reddy. 请修改问题中的内容。 - Amol Raje
我认为问题是如何创建不依赖于特定JPA实现的生成器。看起来JPA没有这样的功能,这很遗憾,因为我认为在JPA中定义它没有问题。 - Marx
显示剩余3条评论
2个回答

21
你可以使用 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;
}
}

7
GenericGenerator来自于Hibernate包,问题是如何在不依赖JPA提供程序的情况下实现。 - Marx
1
@Marx 我认为你需要在 EclipseLink 中使用 SessionCustomizer。JSR 338 中没有提到这种行为。 - LalakaJ
2
在Spring Boot 2.7中使用Hibernate 5.6.9时,您必须使用SharedSessionContractImplementor而不是SessionImplementor - swissbuechi

1
写于:2023年9月15日 上述代码将不再起作用,这是新的代码:
@Override
public Object generate(SharedSessionContractImplementor session, Object object){

    String prefix = "cli";
JdbcConnectionAccess con = session.getJdbcConnectionAccess();
        
            try {
                JdbcConnectionAccess jdbcConnectionAccess = session.getJdbcConnectionAccess();
                Connection connection = jdbcConnectionAccess.obtainConnection();
                Statement statement = connection.createStatement();
                String query = "select count(client_id) as Id from Client";

                ResultSet resultSet = statement.executeQuery(query);

                if (resultSet.next()) {
                     int id=resultSet.getInt(1)+101;
                     String generatedId = prefix + new Integer(id).toString();
                     return generatedId;
                }

                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
return null;
}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接