spring Hibernate不保存FOREIGN KEY(一对多关系)

t98cgbkg  于 2023-04-19  发布在  Spring
关注(0)|答案(1)|浏览(119)

我有2个表(Expert和PhoneNumber)。每个Maven可以有几个数字。这就是为什么我在www.example.com中使用@OneToManyExpert.java,在www.example.com中使用@ManyToOnePhoneNumber.java
由于某种原因,expert_id没有保存到Phone_number表。我做错了什么?
Spring Data JPA和PostgreSQL

数据库架构

CREATE TABLE Expert (
    expert_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(100),
    join_date DATE,
    subscription_expiry_date DATE,
    is_specialist BOOLEAN,
    is_premium BOOLEAN,
    description TEXT,
    photo TEXT
);

CREATE TABLE Phone_number (
    id INT PRIMARY KEY,
    expert_id INT,
    phone_number VARCHAR(20),
    FOREIGN KEY (expert_id) REFERENCES Expert(expert_id)
);

Expert.java

@Entity
@Table(name = "expert")
public class Expert {

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

    // Simple fields

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "expert")
    @Column(name = "phoneNumber")
    private Set<PhoneNumber> phoneNumbers;

    // Getters, setters

电话号码.java

@Entity
@Table(name = "phone_number")
public class PhoneNumber {

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

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "expert_id", referencedColumnName = "expert_id")
    private Expert expert;

    @Column(name = "phone_number")
    private String phoneNumber;

    // Getters, setters

为了与应用程序通信,我使用了JpaRepository接口。

申请

{
    "expertId": 1,
    "phoneNumbers": [
        {
            "phoneNumber": "123-456-7890"
        },
        {
            "phoneNumber": "555-555-5555"
        }
    ]
}

回复

{
    "expertId": 1,
    "phoneNumbers": [
        {
            "id": 2,
            "expert": null,
            "phoneNumber": "555-555-5555"
        },
        {
            "id": 1,
            "expert": null,
            "phoneNumber": "123-456-7890"
        }
    ]
}

ExpertService.java

@Service
public class ExpertService {

    @Autowired
    private ExpertRepository expertRepository;

    public List<Expert> getExperts() {
        return expertRepository.findAll();
    }

    public Optional<Expert> getExpert(Long id) {
        return expertRepository.findById(id);
    }

    public void saveOrUpdateExperts(List<Expert> experts) {
        expertRepository.saveAll(experts);
    }

    public Expert saveOrUpdateExpert(Expert expert) {
        return expertRepository.save(expert);
    }
}
c0vxltue

c0vxltue1#

我通过编辑ExpertService类中的方法设法解决了这个问题

public Expert saveOrUpdateExpert(Expert expert) {
    Set<PhoneNumber> phoneNumbers = expert.getPhoneNumbers();
    phoneNumbers.forEach(phoneNumber -> {
       phoneNumber.setExpert(expert);
    });
    return expertRepository.save(expert);
}

问题是Hibernate首先尝试写入Phone_number,然后写入Expert,因此Phone_number表上的expert_id为null。
谢谢@Mar-Z的帮助:)

相关问题