Hibernate / Spring / JPA-如何使用SELECT子查询插入
给定这个假设的表结构:
person
id | reference | name
book
id | name | person_id
此类结构
@Entity(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id")
Long id;
@Column(name = "name")
String name;
// WHAT GOES HERE?
UUID personReference;
...
}
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
}
在使用 person.id
使用 semalReference使用
book
行时如何插入 book
行在书籍
类上。通常看起来像这样的查询:
insert into book (name, person_id)
values (?, (select id from person p where p.reference = ?))
这是通过注释可以实现的,还是我应该只是实现查询?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Hibernate是 Java持久性API (JPA)的实现,该效果是Java特定的对象关系模型(ORM)。 ORM的目的是将SQL行作为对象&amp;它也包括关系。
但是要将人对象存储在您的数据库中,您也需要拥有一个人实体。
我强烈建议学习JPA的基础知识()
然后,在您的
@repository
class(spring特定)中:最后,在
@service
class(spring特定)中:Hibernate is an implementation of the Java Persistence API (JPA) which is a Java specific Object Relational Model (ORM). The purpose of ORMs is to handle sql rows as objects & it includes relations as well.
But to store Person object in your db, you need to have a Person Entity as well.
I strongly advise to learn the basics of JPA (Specification)
Then, in your
@Repository
classes (Spring specific):Finally, in your
@Service
class (Spring specific):如果没有将人映射为实体,则可以使用本机SQL查询。
我不确定这是否是错误,但是映射应该是:
如果这是有效的本机SQL查询,则可以使用它进行插入:
您的问题不包含足够的信息来弄清楚您是否可以映射
人
作为实体。如果是这种情况,可能会为您提供帮助。If Person is not mapped as an entity, you can use native SQL queries.
I'm not sure if this is an error, but the mapping should be:
If that's a valid native SQL query, you can do the insert using it:
Your question doesn't contain enough info to figure out if you can map
Person
as an entity. If that's the case, this article might help you.