When are generated primary key values available?


JSR 338: JavaTM Persistence 2.1 says, in 3.5.3, that

Generated primary key values are available in the PostPersist method.

It’s a pity that even those ids with GenerationType.TABLE are not available in the PrePersist method and it’s a bigger pity that I didn’t rely on the spec.

public class MyEntity {

    @PrePersist
    private void onPrePersist() {
        derived = Stirng.format("%1$016x", id);
    }

    @GeneratedValue(generator = "some",
                    strategy = GenerationType.TABLE)
    @TableGenerator(
            ...
            name = "some",
            ...
    )
    @NotNull
    private Long id;

    @Basic(optional = false)
    @Column(name = "DERIVED", nullable = false, updatable = false)
    @NotNull
    private String derived;
}

I just found that above code doesn’t work with WildFly while works with Payara.

I have to change my database and the code.

public class MyEntity {

    @PrePersist
    private void onPrePersist() {
        //derived = Stirng.format("%1$016x", id);
    }

    @PostPersist
    private void onPostPersist() {
        derived = Stirng.format("%1$016x", id);
    }

    @GeneratedValue(generator = "some",
                    strategy = GenerationType.TABLE)
    @TableGenerator(
            ...
            name = "some",
            ...
    )
    @NotNull
    private Long id;

    @Basic // optional
    @Column(name = "DERIVED") // nullable, updatable
    //@NotNull
    private String derived;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s