简体   繁体   中英

JPA - Primary key prefix

We have a table where the ID is generated by a trigger -

ID = year+month+sequence

I mapped the table via JPA and I would like to use the same PK generation in my code as well. I tried the following options:

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

and also tried to change the 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);
    }

but non of them worked. I just want to insert new record in the database and do not want to use the id later. I use Hibernate for JPA

You can do this if you implement custom Hibernate generator. This blog has almost identical example to what you need. I'll post here the code from the blog adjusted to your needs (might not work if you copy-paste it, but it will be close)

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;

Hope this helps.

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