hibernate多对一查询

夕拾贰 发布于 2014/07/24 20:02
阅读 1K+
收藏 0
@Entity
@Table(name = "t_dealer_book")
public class DealerBook extends IdEntity {

	protected Book book;
	protected Dealer dealer;
	protected BigDecimal sellPrice;
	protected Date createDatetime;

	@ManyToOne()
	@JoinColumn(name = "book_id", nullable = false)
	public Book getBook() {
		return book;
	}

	public void setBook(Book book) {
		this.book = book;
	}

	@ManyToOne
	@JoinColumn(name = "dealer_id", nullable = false)
	public Dealer getDealer() {
		return dealer;
	}

	public void setDealer(Dealer dealer) {
		this.dealer = dealer;
	}

	public BigDecimal getSellPrice() {
		return sellPrice;
	}

	public void setSellPrice(BigDecimal sellPrice) {
		this.sellPrice = sellPrice;
	}

	public Date getCreateDatetime() {
		return createDatetime;
	}

	public void setCreateDatetime(Date createDatetime) {
		this.createDatetime = createDatetime;
	}

}

Specification的查询

Specification<DealerBook> spec = new Specification<DealerBook>() {
			@Override
			public Predicate toPredicate(Root<DealerBook> dealerBookRoot, CriteriaQuery<?> query, CriteriaBuilder builder) {


				Join dealerJoin = dealerBookRoot.join("dealer", JoinType.INNER);
				Join bookJoin = dealerBookRoot.join("book", JoinType.INNER);

				Predicate dealerId = builder.equal(dealerJoin.get("id").as(Long.class), 100003L);

				Predicate bookId = builder.like(bookJoin.get("bookName").as(String.class), "%实验%");

				List<Predicate> predicates = new ArrayList<Predicate>();
				predicates.add(dealerId);
				predicates.add(bookId);

				return builder.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		};



为什么我现在生成的sql语句会分成两条呢?

select
        dealerbook0_.id as id1_7_,
        dealerbook0_.book_id as book_id4_7_,
        dealerbook0_.create_datetime as create_d2_7_,
        dealerbook0_.dealer_id as dealer_i5_7_,
        dealerbook0_.sell_price as sell_pri3_7_ 
    from
        t_dealer_book dealerbook0_ 
    inner join
        t_dealer dealer1_ 
            on dealerbook0_.dealer_id=dealer1_.id 
    inner join
        t_book book2_ 
            on dealerbook0_.book_id=book2_.id 
    where
        dealer1_.id=100003 
        and (
            book2_.book_name like ?
        ) 
    order by
        dealerbook0_.id desc limit ?



select
        book0_.id as id1_0_0_,
        book0_.author as author2_0_0_,
        book0_.book_name as book_nam4_0_0_,
        。。。。。
    from
        t_book book0_ 
    where
        book0_.id in (
            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
        )



第一条语句不是已经可以直接把Book表的数据拉出来了嘛?

加载中
0
len
len
应该是把一对多中的1+N问题优化成了1+1,第二次查的是关联信息。
返回顶部
顶部