开发者

JPA: Generate a code based on the Auto-incremented id

I have and entity with two fields an id and a code as so...

@Id
@GeneratedValue(strategy = Ge开发者_开发知识库nerationType.AUTO)
@Column(name = "id")
private Integer id;

@Basic
@Column(name = "code", nullable = false)
private String code;

What I would like is to do is, to generate the code based on the Auto-incremented id (Using Mysql as DB).

Is there a way without using a table to generate keys for the code column. i.e

  • id = 1 code is M-000-1
  • id = 2 code is M-000-2 etc..

The only way I have managed to do this is using the script below. Which I am not so sure is the correct way.

getEntityManager().persist(myEntity);
getEntityManager().flush();
myEntity.setCode(myEntity.getCode()+myEntity.getId());
getEntityManager().merge(myEntity);

Thanks in advance! Dimitri


Looks fine. You can perhaps move it to a @PostPersist handler.


You can create a custom sequence generator using the @GenericGenerator annotation. This is specific to Hibernate, but is known to work in JPA.

@Id
@GeneratedValue(generator="custom-code-generator")
@GenericGenerator(name="custom-code-generator", strategy = "classname-of-generator",
parameters={...annotated parameters like the sequence name can be specified here ...})
@Column(name = "id")
private Integer id;

The strategy is to be implemented in a class that implements the PersistentIdentifierGenerator interface, and as noted in the API documentation, custom generators would also implement the Configurable interface to allow for configuration of the generator.

Using the @PostPersist annotation will also work, in that the Id is not flushed to the database until the EntityManager is flushed or if the transaction associated with the EntityManager is committed.


You may try with @PostPersist:

class EntityClass {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @Basic
    @Column(name = "code")
    private String code;

    @PostPersist
    public void generateCode() {
        code = ("M-000-" + id);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜