如何在具有MySQL后端的JPA Spring Boot微服务中为三向关系建模 [英] How to model a three-way relationship in a JPA Spring Boot micro service with a MySQL back end

查看:106
本文介绍了如何在具有MySQL后端的JPA Spring Boot微服务中为三向关系建模的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个带有MySQL后端的Spring Boot JPA微服务.我的模型中有两个简单的实体:用户和技能.这些用于表示我组织中的技能基础.每个用户可能都有很多技能,因此我使用了一对多的联接对此进行建模,并且可以成功地将技能分配给用户.在我的数据库中,我可以看到JPA已经创建了一个users_skills表来实现这一目标.

I have created a Spring Boot JPA micro service with a MySQL back end. I have two simple entities in my model, users and skills. These are used to represent the skills base within my organisation. Each user may have many skills and so I have used a one to many join to model this and can successfully assign skills to users. In my database, I can see that a users_skills table has been created by JPA to achieve this.

但是,我现在很努力,因为对于用户拥有的每种技能,都需要指定经验级别(例如,基本,高级,专家),而我不确定如何实现.我不确定级别"应仅是Skill实体中的枚举类型,还是应该本身就是单独的实体?我可以配置JPA,以便它生成一个user_skills_levels表来表示这种三向关系吗?任何建议都将受到欢迎!

However, I am now struggling because, for each skill that a user has, an experience level needs to be specified (e.g. basic, advanced, expert) and I am unsure how to achieve this. I'm not sure whether 'levels' should just be an enum type within the Skill entity, or perhaps it should be a separate entity in its own right? Could I configure JPA so that it generates a users_skills_levels table which would represent this three-way relationship? Any advice would be most welcome!

这些是我的Entity类:-

These are my Entity classes: -

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

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

    private String name;

    private String email;

    @OneToMany(
            cascade = CascadeType.ALL,
            orphanRemoval = true
    )
    private Set<Skill> skills = new HashSet<>();

    getters and setters
}

@Entity
@Table(name = "skills")
public class Skill {

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

    private String name;

    getters and setters
}

推荐答案

您尝试实现的目标是不可能的.

That's not possible what you try to achieve.

您应该为users_skills_levels创建一个实体.例如. UserSkillLevel此实体将与User之间具有ManyToOne关系,而Skills与属性级别之间具有ManyToOne关系.

You should create an Entity for the users_skills_levels. E.g. UserSkillLevel This entity will then have a ManyToOne relationship to User and a ManyToOne relationship to Skills plus the attribute level.

用户也具有UserSkillLevel和Skill实体的集合.

The User has a collection of UserSkillLevel and the Skill entity as well.

请在此处找到更深入的示例:

Please find a more in-depth example here:

https://thoughts-on-java.org/many- Relationships-additional-properties/

这篇关于如何在具有MySQL后端的JPA Spring Boot微服务中为三向关系建模的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆