如何使用Spring数据JPA与数据库中的非实体表建立外键关系? [英] How to establish foreign key relationship with a non entity table in the database using Spring data JPA?

查看:207
本文介绍了如何使用Spring数据JPA与数据库中的非实体表建立外键关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的spring boot项目使用现有数据库,我的项目中有一个新的模型实体/表,该实体/表必须具有数据库中现有表的外键约束.

My spring boot project uses an existing database, I have a new model entity/table in my project that must have a foreign key constraint with an existing table in the database.

我试图在线找到解决方案,但是所有答案都是针对两个表都作为该项目中的实体存在并使用一些@ ManyToOne,@ OneToMany批注的情况.

I've tried to find solution online but all the answers are for the case where both the tables are present as entities in that project and using some @ManyToOne, @OneToMany annotations.

我无法定义这些批注,因为我的项目中没有引用表作为实体或模型.

I can't define those annotations because I don't have the reference table as an entity or model in my project.

假设我有像这样的课程:

Let's say I have class like:

@Entity(name = "user")
public class User {
    @Id
    @GeneratedValue
    private long userId;
    private long departmentId;

我想在departmentId列上放置一个外键约束以引用现有department表的id列,该表未在我的项目中定义为模型或实体.

I want to put a foreign key contraint on the departmentId column to reference to id column of the existing department table that isn't defined as a model or entity in my project.

谢谢

推荐答案

只需照常进行 例子

@Column(name = "department_id")
private Department departmentId;

您以后可以访问它Department.departmentId.希望这会有所帮助.

You can later access it Department.departmentId. Hope this helps.

这篇关于如何使用Spring数据JPA与数据库中的非实体表建立外键关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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