Hibernate/JPA和PostgreSQL - 主键?

Sha*_*man 11 postgresql hibernate jpa primary-key

我正在尝试使用Hibernate/JPA实现一些基本实体.最初代码部署在MySQL上并且工作正常.现在,我将它移植到使用PostgreSQL.在MySQL中,我的实体类使用以下语法将其主键定义为自动递增的long值:

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试一次插入大量记录时,我发现PostgreSQL出现错误.为了在PostgreSQL中获得与MySQL相同的自动递增行为,我需要注释我的主键是什么?感谢您的任何帮助,您可以提供!

Dan*_*iel 18

GenerationType.IDENTITY


Sha*_*man 10

我已经解决了这个问题.以前 - 在我的MySQL实现中 - 我使用了具有以下签名的抽象基类:

@MappedSuperclass
public abstract class AbstractDomainEntity implements Serializable {

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

        ...
}
Run Code Online (Sandbox Code Playgroud)

......然后我将其扩展到我剩下的每个实体中.我已经将这个属性压缩到实体本身,并将@GenerationType配置为SEQUENCE.例如:

public class UserProfileBean extends AbstractIdentifiedDomainEntitiy {

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

        ...
}
Run Code Online (Sandbox Code Playgroud)

通过这样做,在Hibernate/JPA和PostgreSQL中生成并使用了正确的序列.之前,即使我将GenerationType声明为Sequence,也没有创建.感谢您在这件事上的所有帮助和建议!