添加具有多对多关系的实体并具有相关实体的代理

时间:2019-01-12 19:28:03

标签: hibernate jpa

我很好奇,如果可以添加实体并与其他实体建立关系,只需通过getReference方法获得代理即可。

我的实体如下

@Entity
@Table(name = "BOOK")
@NamedQuery(name="Book.findAll", query = "SELECT b from Book as b LEFT JOIN b.discountList as d where d.endingDate is null")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private Long bookId;

    @Column(name = "TITLE")
    private String title;

    @Column(name = "ISBN")
    private String isbn;

    @Column(name = "DESCRIPTION")
    @Type(type="text")
    private String description;

    @Column(name = "PUBLISHING_DATE")
    private Date publishingDate;

    @Column(name = "BASE_PRICE")
    private BigDecimal basePrice;

    @ManyToMany(fetch = FetchType.LAZY, cascade = {
            CascadeType.MERGE,
            CascadeType.PERSIST
    })
    @JoinTable(name = "BOOK_TO_DISCOUNT",
            joinColumns = {@JoinColumn(name = "book_id")},
            inverseJoinColumns = {@JoinColumn(name = "discount_id")})
    private Set<Discount> discountList;
}

@Entity
@Table(name = "DISCOUNT")
public class Discount {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private Long discountId;

    @Column(name = "NAME")
    private String name;

    @Column(name = "RATE")
    private Integer rate;

    @Column(name = "START_DATE")
    private Timestamp startingDate;

    @Column(name = "END_DATE")
    private Timestamp endingDate;

    @ManyToMany(fetch = FetchType.LAZY,
            mappedBy = "discountList")
    private Set<Book> bookList;

}

我的目标是添加与某些书籍相关的折扣,因此我需要在DISCOUNT表中插入新的促销信息,并将关系添加到BOOK_TO_DISCOUNT表中。

现在,我以这种方式执行此操作:

Set<Book> listOfLinkedBooks = discountData.getIdsOfBooksCoveredByThisDiscount().stream()
                .map(idOfBook -> entityManager.find(Book.class, idOfBook)).collect(Collectors.toSet());

        Discount discount = new Discount(discountData.getDiscountId(),
                discountData.getName(),
                discountData.getRate(),
                discountData.getStartingDate(),
                discountData.getEndingDate(),
                listOfLinkedBooks);

        listOfLinkedBooks.forEach(a -> {
            Optional.ofNullable(a.getDiscountList()).orElseGet(Collections::emptySet)
                    .add(discount);
        });
        entityManager.merge(discount);

该解决方案的缺点在于使用find方法,因为当仅需要实体映射与其连接的关系时,休眠状态会获取实体的所有数据。从数据库的角度看,ID足以完成此操作。有没有机会使用getRelation方法来做到这一点?

另一个优化此操作的解决方案是手动添加新关系,因此我应该为BOOK_TO_DISCOUNT表创建一个实体,然后手动插入新关系。我认为这个想法很肮脏,实现涉及创建更多实体。这就是为什么我在这种情况下询问用法getRelation的原因。

0 个答案:

没有答案