与继承对象的多对一关系-Postgres

时间:2019-03-07 23:06:06

标签: spring jpa inheritance spring-data-jpa mapping

我正在构建一个需要单个登录页面的应用程序。但是,有两种“类别”的用户:客户和培训师。我的域如下所示:

      User
        |
  +-----+-----+
  |           |
Person     Trainer

我的用户将包含电子邮件,密码等,因此我可以使用此表来验证我的登录请求。

培训师应存储人员列表,一个人应拥有1位培训师。

一对多的工作原理,培训师可以存储Person类对象的列表,但是我无法通过客户端链接回培训师。

这是我的User类:

package com.example.demo.model;

import javax.persistence.*;

@Entity
@Inheritance
@Table(name="users")
public abstract class User {

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

    private String email;

    public User(){}

    public User(String email) {
        this.email = email;
    }


    public Long getId() {
        return id;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Person类:

package com.example.demo.model;

import javax.persistence.*;

@Entity
public class Person extends User {

    @Column
    private int age;

    @ManyToOne
    @JoinColumn
    private Trainer trainer;

    public Person(){}

    public Person(String email, int age) {
       super(email);
        this.age = age;
    }
}

培训师课程:

package com.example.demo.model;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
public class Trainer extends User {

    @Column
    private String description;

    @OneToMany(mappedBy = "trainer", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Person> clients;

    public Trainer(){}

    public Trainer(String email, String description) {
        super(email);
        this.description = description;
    }

    public void addClient(Person person){
        this.clients = new ArrayList<>();
        this.clients.add(person);
    }
}

我应该如何通过ManyToOne注释访问客户的培训师?还是还有其他选择? 预先感谢!

1 个答案:

答案 0 :(得分:1)

不初始化addClient()中的列表。您正在覆盖/删除现有客户端。在字段声明中执行。

@OneToMany(...)
private List<Person> clients = new ArrayList<>();

设置双方关系:

public void addClient(Person person){
    person.setTrainer(this);
    this.clients.add(person);
}