user390517
user390517

Reputation:

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 = GenerationType.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

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

Upvotes: 2

Views: 2651

Answers (3)

Vineet Reynolds
Vineet Reynolds

Reputation: 76719

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.

Upvotes: 1

Nicolae Albu
Nicolae Albu

Reputation: 1245

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);
    }
}

Upvotes: 0

Bozho
Bozho

Reputation: 597382

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

Upvotes: 2

Related Questions