繁体   English   中英

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

[英]Hibernate / Spring / JPA - How to insert with a select subquery

给定这个假设的表结构:

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

如何在使用Book类上的personReference字段选择person.id时插入book行。 查询通常如下所示:

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

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

如果 Person 未映射为实体,则可以使用本机 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);

您的问题没有包含足够的信息来确定您是否可以将Person映射为实体。 如果是这种情况, 这篇文章可能会对您有所帮助。

Hibernate 是Java Persistence API (JPA) 的实现,它是 Java 特定的对象关系模型(ORM)。 ORM 的目的是将 sql 行作为对象处理,它也包括关系。

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

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

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

    String name;

}
   

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

然后,在您的@Repository类(特定于 Spring)中:

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

}

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

}

最后,在您的@Service类(特定于 Spring)中:

@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);
    }
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM