【问题标题】:Spring Data: How to set GenerationType strategy while working with @Embeddable and @EmbeddedSpring Data:如何在使用 @Embeddable 和 @Embedded 时设置 GenerationType 策略
【发布时间】:2017-02-08 14:59:09
【问题描述】:

我正在尝试在 Spring 数据中使用 @Embeddable@Embedded。以下是我的方法。

设备实体:

@Entity
@Table(name = "device")
public class DeviceEntity implements Serializable {


      private static final long serialVersionUID = 1L;

      @EmbeddedId
      @AttributeOverrides({@AttributeOverride(name = "id" , column= @Column(name = "id",nullable = false))})
      private DeviceIdType deviceIdType;

.

DeviceIdType:

@Embeddable
public class DeviceIdType implements Serializable {

  private static final long serialVersionUID = 1L;

  @Column(name = "id")
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;

。 . .

错误信息:

"code": "4715",
  "message": "Something went wrong",
  "additionalInfo": "null id generated for:class com.b.DeviceEntity; nested exception is org.hibernate.id.IdentifierGenerationException: null id generated for:class com.b.DeviceEntity"

现在,当我使用 GenertionType 策略时,我得到了这个异常。

因此,我的问题是:在使用@Embeddable 和@Embedded 时如何设置GenerationType 策略?

【问题讨论】:

标签: java hibernate spring-boot spring-data-jpa


【解决方案1】:

@Embeddable@EmbeddedId 在大多数情况下用于 JPA / Spring Data 中的复合主键。

如果你有一个简单的生成主键,你最好使用@Id注解和@GenerationType

【讨论】:

  • @Id 不适用于嵌入对象(值类型)。它仅适用于实体。
  • 没错,但在他的情况下,他只是嵌入了一个long,可以在主实体类中设置
  • 如果你这么看,那么是的。 id 可能只是 DeviceEntity 的一部分,而不是 Embeddable 对象,但这完全取决于他的设计,即他是否打算拥有其他需要更好的 OOP 方法的字段。
猜你喜欢
  • 2016-01-26
  • 1970-01-01
  • 2021-02-05
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 2011-03-28
  • 2012-11-07
  • 2019-07-05
相关资源
最近更新 更多