gpt4 book ai didi

java - @OneToOne 单向映射中的实体映射中的重复列

转载 作者:行者123 更新时间:2023-12-02 10:10:53 27 4
gpt4 key购买 nike

考虑以下数据库结构

我需要像这样实现单向一对一映射(结构已简化):

@Entity
@Table(name = "entity")
public class Customer {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@OneToOne
@JoinColumn(name = "customer_info", nullable = false)
private CustomerInfo customerInfo;

@OneToOne
@JoinColumn(name = "customer_credentials", nullable = false)
private CustomerCredentials customerCredentials;

// getter, setters etc
}

@Entity
@Table(name = "customer_info")
public class CustomerInfo {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

// getter, setters etc
}

@Entity
@Table(name = "customer_credentials")
public class CustomerCredentials {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

// getter, setters etc
}

但不知何故,hibernate 无法区分这些连接来自不同的表并抛出这样的错误:

Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.example.Customer column: customer_id (should be mapped with insert="false" update="false")

重要通知:我不想使用@OneToOne(mappedBy = "customer"),因为我需要级联保存功能

最佳答案

您可以使用@JoinTable代替@JoinColumn来解决您的问题:

@Entity @Table(name = "entity") public class Customer {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@OneToOne(cascade = CascadeType.ALL, targetEntity = CustomerInfo.class)
@JoinTable(name = "customer_info", inverseJoinColumns = {@JoinColumn(name = "customer_id", nullable = false)})
private CustomerInfo customerInfo;

@OneToOne(cascade = CascadeType.ALL, targetEntity = CustomerCredentials.class)
@JoinTable(name = "customer_credentials", inverseJoinColumns = {@JoinColumn(name = "customer_id", nullable = false)})
private CustomerCredentials customerCredentials;

// getter, setters etc }

@Entity @Table(name = "customer_info") public class CustomerInfo {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

// getter, setters etc }

@Entity @Table(name = "customer_credentials") public class CustomerCredentials {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

// getter, setters etc }

您可以将级联策略更改为您需要的任何策略。我只是将 CascadeType.ALL 留在那里作为示例。

关于java - @OneToOne 单向映射中的实体映射中的重复列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55010887/

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