简体   繁体   English

冬眠。 如何使用条件从联接表中进行查询?

[英]Hibernate. How to make query from a joined table using Criteria?

I have 2 tables: 我有2张桌子:

|shops        |       |discounts    |
|-------------|       |-------------|
|id           |       |id           |
|name         |       |title        |
                      |shop_id      |

*UML Diagram * UML图

And entities: 和实体:

@Entity
@Table(name = "shops")
public class Shops {
  @Id
  @GeneratedValue
  @Column(name="id", unique=true, nullable=false)
  protected Integer id;

  @Column(name="name", length=45, nullable=false)
  protected String name;

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "shop")
  private Set<Discounts> discounts = new HashSet<Discounts>(0);
        //getters & setters
}

@Entity
@Table(name="discounts")
public class Discounts {
@Id
  @GeneratedValue
  @Column(name="id")
  private Integer id;

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

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "shop_id", nullable = false)
  private Shops shop;
        //getters & setters
}

I need to receive all discounts which belong to a shop usingCriteria. 我需要接收所有使用Criteria的商店的折扣。 I try to make it as follows: 我尝试使其如下:

Criteria cr = session.createCriteria(Discounts.class);
cr.add(Restrictions.eq("id", shop.getLocality()));
List<Discounts> discounts = cr.list();

But I get an error: 但是我得到一个错误:

java.lang.ClassCastException: exmp.entity.Discounts_$$_jvste43_1 cannot be cast to java.lang.Integer

How can I fix this error? 如何解决此错误?

You can do this: 你可以这样做:

Criteria cr = session.createCriteria(Discounts.class);
cr.add(Restrictions.eq("shop", shop)); //assuming shop is an object of Shops
List<Discounts> discounts = cr.list();

This will internally map the id column of Shops to shop column of Discounts to check the constraints and return results. 这将在内部将“ Shopsid列映射到“ Discounts shop列,以检查约束并返回结果。

The documentation says that idEq applies to an identifier property. 该文档说idEq适用于标识符属性。

https://docs.jboss.org/hibernate/core/3.3/api/org/hibernate/criterion/Restrictions.html#idEq(java.lang.Object) https://docs.jboss.org/hibernate/core/3.3/api/org/hibernate/criterion/Restrictions.html#idEq(java.lang.Object)

Instead you can try something like this: 相反,您可以尝试如下操作:

Criteria cr = session.createCriteria(Discounts.class);
cr.createAlias("shop","shop") 
cr.add(Restrictions.eq("shop.id",<yourid>));

But if you just load a shop with its id, you will be getting the all the discounts of that shop since you have bidirectional relationship. 但是,如果仅使用ID为其加载商店,则由于具有双向关系,您将获得该商店的所有折扣。

Criteria cr = session.createCriteria(Shops.class);
cr.add(Restrictions.idEq(<yourid>));

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

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