JPA:不可变ID的AccessType.PROPERTY

时间:2018-01-08 11:20:35

标签: java spring hibernate jpa

我有一个实体结构:

allprojects {
repositories {
    maven {
        url 'https://maven.google.com'
    }
}
}

我在other answers中读到,@Entity @Table(name = "Book") public class Book { @Id @Access(AccessType.PROPERTY) @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "AUT_ID") @Fetch(FetchMode.JOIN) private Author author; Book(){} public Book(Author author) { this.author = author; } public Long getId() { return this.id; } public Author getAuthor() { return this.author; } } @Entity @Table(name = "Author") public class Author { @Id @Access(AccessType.PROPERTY) @GeneratedValue(strategy= GenerationType.AUTO) private Long id; @OneToMany(mappedBy = "author", fetch = FetchType.LAZY) private List<Book> books; Author(){} public Long getId() { return this.id; } public List<Book> getBooks() { return this.books; } } 字段@Id允许我执行以下操作:

@Access(AccessType.PROPERTY)

只有一个查询将对数据库进行,因为作者// BookRepository is just a CrudRepository<Book,Long> Book book = bookRepository.findById(1L); // Triggers a Select Query Long authorId = book.getAuthor().getId(); // Does not trigger a query 已经从初始选择加载。

当我这样做并启动我的Spring Boot应用程序时,我得到:

  

org.hibernate.PropertyNotFoundException:找不到属性的setter方法[com.demo.repository.persistance.entity.Book #id]

     

org.hibernate.PropertyNotFoundException:找不到属性的setter方法[com.demo.repository.persistance.entity.Author #id]

这可能意味着我需要在ID上使用setId方法,我宁愿不这样做,因为它会使Entities变得可变。有没有办法可以获得ID Access的好处(即没有对子对象的Property进行额外的查询)并保持getId不可变?

如果我删除了我的SQL日志的ID注释:

Access

1 个答案:

答案 0 :(得分:0)

@Access(AccessType.PROPERTY)表示JPA在选择之后或插入或更新之前调用getter和setter来访问该字段。

如果您在某些情况下只需要authorId,那么只能在Book实体中将其映射为只读:

@Column(name = "aut_id", insertable = false, updatable = false)
private Long authorId;