Hibernate / Spring / JPA-如何使用SELECT子查询插入

发布于 2025-02-06 15:31:03 字数 779 浏览 2 评论 0 原文

给定这个假设的表结构:

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 = ?))

这是通过注释可以实现的,还是我应该只是实现查询?

Given this hypothetical table structure:

person
id | reference | name

book
id | name | person_id

And this class structure

@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> {
}

How would one insert the book row while using a select the person.id using the personReference field on the Book class. A query that would usually look like this:

insert into book (name, person_id)
values (?, (select id from person p where p.reference = ?))

Is this something that is possible through annotations or should I look to just implement a query?

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

那小子欠揍 2025-02-13 15:31:03

Hibernate是 Java持久性API (JPA)的实现,该效果是Java特定的对象关系模型(ORM)。 ORM的目的是将SQL行作为对象&amp;它也包括关系。

@Entity
public class Book implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    Long id;

    String name;

    // relational mapping
    @ManyToOne // an author can write multiple books. but a book has a single author
    Person author; // an author is a Person not an UUID
}

但是要将人对象存储在您的数据库中,您也需要拥有一个人实体。

@Entity
public class Person implements Serializable {
    
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    long id; // primitive types can be primary keys too

    String name;

}
   

我强烈建议学习JPA的基础知识(

然后,在您的@repository class(s​​pring特定)中:

@Repository
public BookRepository implements CrudRepository<Book,Long> {    

}

@Repository 
public PersonRepository implements CrudRepository<Book,Long> {

}

最后,在 @service class(s​​pring特定)中:

@Service
public class BookService {

    
    PersonRepository personRepo;
    BookRepository bookRepo;

    public BookService(PersonRepository personRepo, BookRepository bookRepo) {
        this.personRepo = personRepo;
        this.bookRepo = bookRepo;
    }

    public void setBookAuthor(Book book, Person author) {
        book.setAuthor(author);
        bookRepo.save(book);
    }

    public void setBookAuthor(long bookId, long personId) {
        Book book = bookRepo.findById(bookId);
        Person author = userRepo.findById(personId);
        setBookAuthor(book, author);
    }
} 

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.

@Entity
public class Book implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    Long id;

    String name;

    // relational mapping
    @ManyToOne // an author can write multiple books. but a book has a single author
    Person author; // an author is a Person not an UUID
}

But to store Person object in your db, you need to have a Person Entity as well.

@Entity
public class Person implements Serializable {
    
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    long id; // primitive types can be primary keys too

    String name;

}
   

I strongly advise to learn the basics of JPA (Specification)

Then, in your @Repository classes (Spring specific):

@Repository
public BookRepository implements CrudRepository<Book,Long> {    

}

@Repository 
public PersonRepository implements CrudRepository<Book,Long> {

}

Finally, in your @Service class (Spring specific):

@Service
public class BookService {

    
    PersonRepository personRepo;
    BookRepository bookRepo;

    public BookService(PersonRepository personRepo, BookRepository bookRepo) {
        this.personRepo = personRepo;
        this.bookRepo = bookRepo;
    }

    public void setBookAuthor(Book book, Person author) {
        book.setAuthor(author);
        bookRepo.save(book);
    }

    public void setBookAuthor(long bookId, long personId) {
        Book book = bookRepo.findById(bookId);
        Person author = userRepo.findById(personId);
        setBookAuthor(book, author);
    }
} 
阪姬 2025-02-13 15:31:03

如果没有将人映射为实体,则可以使用本机SQL查询。

我不确定这是否是错误,但是映射应该是:

@Column(name="person_id")
UUID personReference;

如果这是有效的本机SQL查询,则可以使用它进行插入:

@Modifying
@Query(nativeQuery=true, value="insert into book (name, person_id) values (?1, (select id from person p where p.reference = ?2))")
public int insert(String name, String reference);

您的问题不包含足够的信息来弄清楚您是否可以映射作为实体。如果是这种情况,可能会为您提供帮助。

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:

@Column(name="person_id")
UUID personReference;

If that's a valid native SQL query, you can do the insert using it:

@Modifying
@Query(nativeQuery=true, value="insert into book (name, person_id) values (?1, (select id from person p where p.reference = ?2))")
public int insert(String name, String reference);

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文