Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate/JPA and PostgreSQL - Primary Key?

I'm trying to implement some basic entities using Hibernate/JPA. Initially the code was deployed on MySQL and was working fine. Now, I'm porting it over to use PostgreSQL. In MySQL, my entity class defines its primary key as an auto-incrementing long value with the following syntax:

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

However, I've found that I get errors with PostgreSQL when I try and insert numerous records at a time. What do I need to annotate my primary key with to get the same auto-incrementing behavior in PostgreSQL as I have with MySQL? Thanks for any help you can provide!

like image 956
Shadowman Avatar asked May 12 '10 23:05

Shadowman


2 Answers

GenerationType.IDENTITY

like image 138
Daniel Avatar answered Oct 20 '22 00:10

Daniel


I've solved the issue. Previously -- in my MySQL implementation -- I made use of an abstract base class with the following signature:

@MappedSuperclass
public abstract class AbstractDomainEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id = null;

        ...
}

...and then I extended this in each of my remaining entities. I've since pushed this attribute down into the entities themselves, and configured the @GenerationType as SEQUENCE. For example:

public class UserProfileBean extends AbstractIdentifiedDomainEntitiy {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "profile_seq")
    @SequenceGenerator(name = "profile_seq", sequenceName = "profile_seq")
    private Long id = null;

        ...
}

By doing so, the proper sequences are being generated and utilized within Hibernate/JPA and PostgreSQL. Before, even if I declared the GenerationType as Sequence, none was being created. Thanks for all of your help and advice in this matter!

like image 40
Shadowman Avatar answered Oct 19 '22 23:10

Shadowman