我想在JPA中生成自定义ID,它必须是表的主键。有许多使用Hibernate创建自定义ID的示例,例如这个。我想要相同的实现,但在JPA中。该ID必须是字母数字混合的,例如STAND0001
。
谢谢。
我想在JPA中生成自定义ID,它必须是表的主键。有许多使用Hibernate创建自定义ID的示例,例如这个。我想要相同的实现,但在JPA中。该ID必须是字母数字混合的,例如STAND0001
。
谢谢。
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;
}
}
SharedSessionContractImplementor
而不是SessionImplementor
。 - swissbuechi@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;
}}