JPA - 主键前缀

时间:2014-12-29 14:27:28

标签: java jpa

我们有一个表格,其中ID由触发器生成 -

  

ID =年+月+序列

我通过JPA映射表,我也想在我的代码中使用相同的PK生成。我尝试了以下选项:

    @Id
    @SequenceGenerator(name = "assetSeq", sequenceName = "ASSET_SEQ")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "assetSeq")
    @Transient
    private long id;

并且还尝试更改了setter

   public void setId(long id) {

        String finalId=getIdPrefix()+id;
        this.id = Long.parseLong(finalId);

    }

    private String getIdPrefix() {
        DateFormat df = new SimpleDateFormat("YYYYMM");
        Date today = Calendar.getInstance().getTime();
        return df.format(today);
    }

但他们没有工作。我只是想在数据库中插入新记录,不想以后使用id。我使用Hibernate for JPA

1 个答案:

答案 0 :(得分:1)

如果您实现自定义Hibernate生成器,则可以执行此操作。 This blog几乎与您的需求相同。我会在这里发布根据您的需求调整的博客代码(如果您复制粘贴它可能不起作用,但它会关闭)

public class CustomIdGenerator implements IdentifierGenerator {

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

        String prefix = getIdPrefix();
        Connection connection = session.connection();
        try {

            PreparedStatement ps = connection
                    .prepareStatement("SELECT nextval ('ASSET_SEQ') as nextval"); // could be different, depending on database vendor

            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                int id = rs.getInt("nextval");
                String code = prefix + id;
                return code;
            }

        } catch (SQLException e) {
            throw new HibernateException(
                    "Unable to generate ID");
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Throwable e) {
                    // log error, or rethrow exception
                }
            }
        }
        return null;
    }

    private String getIdPrefix() {
        DateFormat df = new SimpleDateFormat("YYYYMM");
        Date today = Calendar.getInstance().getTime();
        return df.format(today);
    }

}

@Id
@GenericGenerator(name="seq_id", strategy="my.package.CustomIdGenerator")
@GeneratedValue(generator="seq_id")
// don't put that @Transient here
private long id;

希望这有帮助。