JPA Hibernate:使用外键发布和获取

发布于 2025-01-17 19:57:29 字数 662 浏览 1 评论 0原文

我使用 Spring,也使用 Hibernate 来设置 RESTful 服务。不幸的是,当我只有相关的外键时,我不知道如何处理弱实体的表。

我认为,这很难解释,让我举个例子:

假设我们有 Person 类和 Dog 类。每只存在的狗都有一个人作为主人。一个人不必拥有一只狗。然而,一个人可以拥有任意数量的狗。

不幸的是,我无法向您展示任何代码,因为 ctrl+k 或代码标签不起作用,但 Person 和 Dog 都有层:

在包 com.example.person 中: 人, 人员控制器, 人员服务, com.example.dog 包中的PersonRepository

: 狗, 狗控制器, 狗服务, DogRepository

现在,我在 DogService.java 中。我想做两件事:

  1. 获取一个人的所有狗,只需拥有该人的 id: 我的第一个想法是使用 DogRepository 中的 Query 注释来执行类似“... WHERE d.person = ?1”的操作。但我不知道具体该怎么做。
  2. 使用 Person 的 id 发布一条狗: 如何使用人员 ID 将某些内容保存到存储库?通常我会使用dogRepository。节省(...)。

在我的脑海里,它就像狗和人之间的一堵看不见的墙。请你帮助我好吗?

非常感谢!

I am using Spring, but also Hibernate to set up a RESTful service. Unfortunately, I don't know how to work on the weak entity's table when I just have the related foreign key.

I think, it is difficult to explain, let me give you an example:

Imagine we have the class Person and the class Dog. Every Dog that exists has exactly one Person as owner. A Person don't have to own a Dog. However, a Person can have as many Dogs as he or she wants.

Unfortunately, I am not able to show you any code because ctrl+k, or code tags doesn't work, but there are layers for both, Person and Dog:

in Package com.example.person:
Person,
PersonController,
PersonService,
PersonRepository

in Package com.example.dog:
Dog,
DogController,
DogService,
DogRepository

Now, I am in DogService.java. I want to do two things:

  1. Get all dogs of a Person just having the Person's id:
    My first idea was to use the Query annotation in DogRepository to do something like "... WHERE d.person = ?1". But I don't know exactly how to do that.
  2. Post a dog by using the id of the Person:
    How can I save something to the Repository by using the Person's id? Ususally I would use dogRepository. save(...).

It is like an invisible wall between dog and person in my head. Could you please help me?

Thank you very much!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文