如何将一组 java 对象表示为数据库中其他对象的字段?

我有一堂运动和训练课。我想在每次培训中进行一组练习。我的问题是——如何在数据库和 Java 中表示?


我想到的是根据表training_id中的外键在特定训练中添加一个练习exercise。但我想将每个练习存储在一组训练中,或者只列出训练课程的一个领域——我认为这是这样做的好方法,但我可能是错的。


@Entity

@Table(name = "exercise")

public class Exercise {


    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    @Column(name = "exercise_id")

    private int id;


    @Column(name = "exercise_name")

    private String name;


    @Column(name = "weight")

    private double weight;


    @Column(name = "series")

    private int series;


    @Column(name = "training_id")

    private int trainingId;

@Table(name = "training")

public class Training {


    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    @Column(name = "training_id")

    private int id;


    @Column(name = "training_name")

    private String trainingName;


    @Column(name = "date")

    private Date date;


    private Set<Exercise> exercises;


也许我不明白它的概念。谁能告诉我正确的方法吗?


白板的微信
浏览 130回答 1
1回答

慕无忌1623718

试试这个:@Table(name = "training")public class Training {&nbsp; &nbsp; @Id&nbsp; &nbsp; @GeneratedValue(strategy = GenerationType.IDENTITY)&nbsp; &nbsp; @Column(name = "training_id")&nbsp; &nbsp; private int id;&nbsp; &nbsp; @Column(name = "training_name")&nbsp; &nbsp; private String trainingName;&nbsp; &nbsp; @Column(name = "date")&nbsp; &nbsp; private Date date;&nbsp; &nbsp; @OneToMany(mappedBy = "training")&nbsp; &nbsp; private Set<Exercise> exercises = new HashSet<>();@Entity@Table(name = "exercise")public class Exercise {&nbsp; &nbsp; @Id&nbsp; &nbsp; @GeneratedValue(strategy = GenerationType.IDENTITY)&nbsp; &nbsp; @Column(name = "exercise_id")&nbsp; &nbsp; private int id;&nbsp; &nbsp; @Column(name = "exercise_name")&nbsp; &nbsp; private String name;&nbsp; &nbsp; @Column(name = "weight")&nbsp; &nbsp; private double weight;&nbsp; &nbsp; @Column(name = "series")&nbsp; &nbsp; private int series;&nbsp; &nbsp; @Column(name = "training_id")&nbsp; &nbsp; private int trainingId;&nbsp; &nbsp; @ManyToOne&nbsp; &nbsp; @JsonIgnoreProperties("exercises")&nbsp; &nbsp; private Training training;这将是外键引用的 2 个单独的数据库。编辑:这将是外键引用的2 个单独的表(不是数据库)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java