Hibernate/JPA 和 PostgreSQL - 主键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2823396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate/JPA and PostgreSQL - Primary Key?
提问by Shadowman
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:
我正在尝试使用 Hibernate/JPA 实现一些基本实体。最初,代码部署在 MySQL 上并且运行良好。现在,我正在移植它以使用 PostgreSQL。在 MySQL 中,我的实体类使用以下语法将其主键定义为自动递增的 long 值:
@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!
但是,我发现当我尝试一次插入大量记录时,PostgreSQL 会出错。我需要用什么来注释我的主键才能在 PostgreSQL 中获得与 MySQL 相同的自动递增行为?感谢您的任何帮助,您可以提供!
采纳答案by Shadowman
I've solved the issue. Previously -- in my MySQL implementation -- I made use of an abstract base class with the following signature:
我已经解决了这个问题。以前——在我的 MySQL 实现中——我使用了一个具有以下签名的抽象基类:
@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:
...然后我将其扩展到我剩余的每个实体中。我已经将此属性推入实体本身,并将@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;
...
}
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!
通过这样做,可以在 Hibernate/JPA 和 PostgreSQL 中生成和使用正确的序列。之前,即使我将 GenerationType 声明为 Sequence,也不会创建任何一个。感谢您在这件事上的所有帮助和建议!
回答by Daniel
GenerationType.IDENTITY
生成类型.IDENTITY