gpt4 book ai didi

java - hibernate 主键的原语或包装器

转载 作者:IT老高 更新时间:2023-10-28 20:51:57 25 4
gpt4 key购买 nike

我一直在看各种hibernate教程和示例,对于它们的身份/主键属性,有些使用Java原始类型,有些使用包装器类型,即;

 private int id; 

 private Integer id;

我为什么以及何时将一个而不是另一个用于实体键?

最佳答案

从 Hibernate 的角度来看,它不会改变任何东西,因为 Hibernate 使用相同的 Hibernate 类型来表示它们。

但是,正如 Bytecode Ninja 所指出的,您无法将原始 int 0 的默认值与分配的 0 区分开来,但不会有歧义使用 null (null id 总是意味着一个新实体),这就是为什么我更喜欢使用可为空的包装器类型。

这是 Hibernate 的建议。来自引用文档:

4.1.2. Provide an identifier property (optional)

Cat has a property called id. This property maps to the primary key column of a database table. The property might have been called anything, and its type might have been any primitive type, any primitive "wrapper" type, java.lang.String or java.util.Date. If your legacy database table has composite keys, you can use a user-defined class with properties of these types (see the section on composite identifiers later in the chapter.)

The identifier property is strictly optional. You can leave them off and let Hibernate keep track of object identifiers internally. We do not recommend this, however.

In fact, some functionality is available only to classes that declare an identifier property:

  • Transitive reattachment for detached objects (cascade update or cascade merge) - see Section 10.11, “Transitive persistence”
  • Session.saveOrUpdate()
  • Session.merge()

We recommend that you declare consistently-named identifier properties on persistent classes and that you use a nullable (i.e., non-primitive) type.

我实际上在我的基类中利用了这一点:

@MappedSuperclass
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

@Transient
public boolean isNew() {
return (this.id == null);
}
}

关于java - hibernate 主键的原语或包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3535791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com