JPA EntityManager设置列表循环

时间:2018-06-10 18:25:31

标签: java jpa

我有以下问题。看看我的课程和代码,我将描述问题。

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Book {

    @Id
    @SequenceGenerator(name = "book_id_seq_gen", sequenceName = "book_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "book_id_seq_gen")
    private long id;
    private String name;
    private int year;
    @ManyToOne
    private Writer writer;
    private String description;
    private int downloadNumber;
    @ManyToMany
    @JoinTable(name = "book_genre",
            joinColumns = @JoinColumn(name = "book_id"),
            inverseJoinColumns = @JoinColumn(name = "genre_id")
    )
    private Set<Genre> genres;
}


@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Writer {

    @Id
    @SequenceGenerator(name = "writer_id_seq_gen", sequenceName = "writer_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "writer_id_seq_gen")
    private long id;
    @NotNull(message = "Name cannot be null")
    @Length(min = 1, max = 100)
    private String name;
    @NotNull(message = "Surname cannot be null")
    @Length(min = 1, max = 100)
    private String surname;
    private String description;
    @Transient
    private List<Book> books;
}


@Repository
public class WriterDao {

    @PersistenceContext
    private EntityManager entityManager;

    public Writer selectUserById(long writerId) {
        Writer writer = entityManager.find(Writer.class, writerId);
        TypedQuery<Book> query = entityManager.createQuery("SELECT b FROM Book b WHERE b.writer.id = :writerId", Book.class);
        query.setParameter("writerId", writerId);
        //entityManager.detach(writer);
        writer.setBooks(query.getResultList());
        return writer;
    }
}

我正在尝试选择书籍并将其设置为作者,但我正在进行循环。但是,当我分离我的作家,然后设置它的作品。为什么?我想我知道为什么会出现一个循环,但我不明白。

0 个答案:

没有答案