用hibernate加入外键

pit*_*tic 2 java hibernate

我是一个hibernate-beginner,在尝试使用hibernate加入2个表时遇到问题.我想要做的是根据商店ID获取某个商店的产品列表,但我得到的是每个商店下列出的数据库中所有可用产品的列表.

这是以下代码Product.java:

@Entity
@Table (name = "products")
public class Product implements Serializable{

/**
 * 
 */
private static final long serialVersionUID = -1001086120280322279L;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column (name = "product_id")
private int product_id;

@Column(name = "product_name", unique=true)
private String product_name;

@JoinColumn(name = "store", referencedColumnName="store_id")
@ManyToOne(cascade=CascadeType.ALL)
private Store store;
Run Code Online (Sandbox Code Playgroud)

等等..

这是以下代码Store.java:

@Entity
@Table(name = "stores")
public class Store implements Serializable{
/**
 * 
 */
private static final long serialVersionUID = 4497252090404342019L;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column (name = "store_id")
private int store_id;

@Column(name = "store_name", unique=true)
private String store_name;

@JoinColumn(name="store", referencedColumnName= "store_id")
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
private List<Product> productList;
Run Code Online (Sandbox Code Playgroud)

等等..

这是输出:(产品A应在Butik A下,产品B在Butik B下)

Butik: Butik A
Produkt: Banana A
Produkt: Morot A
Produkt: Banana B
Produkt: Apple B

Butik: Butik B
Produkt: Banana A
Produkt: Morot A
Produkt: Banana B
Produkt: Spple B
Run Code Online (Sandbox Code Playgroud)

我有2个额外的类,ProductDAO和StoreDAO负责查询,除了table-name/class-name之外,两个类中的代码类似.

public class ProductDAO { 
   public static List<Product> getStoreProductsList() { 
     Session hibernateSession = HibernateUtil.getSession(); 
     hibernateSession.beginTransaction();    
     Query query = hibernateSession.createQuery("from Product");
     hibernateSession.getTransaction().commit();     
     List<Product> storeProducts = query.list(); 
     return storeProducts;   
   }
}
Run Code Online (Sandbox Code Playgroud)

有什么办法只用hibernate来解决这个问题吗?

谢谢

Ade*_*ari 7

完成你的评论后.看起来你从来没有在那里设定条件,当然,无论他们属于哪个商店,你最终都会获得所有产品.没有惊喜.你在哪里指定标准?

你可以做点什么,

// One liner
List<Product> list = session.createQuery("from Product p where p.store.store_id = "
          +" :storeId").setInteger("storeId", storeId).list();
Run Code Online (Sandbox Code Playgroud)

或者你可以得到Store,然后得到如下的列表Product,

// Another one liner
List<Product> list = session.createCriteria(Store.class)
             .add(Restrictions.eq("store_id", storeId)).list().getProductList();
Run Code Online (Sandbox Code Playgroud)

另一种更简单的方法,因为我们知道store_id是主键,(感谢Pakore提醒我)

// And another. Changed to use load() instead of get() here. 
// Assuming non-existance is an error.
List<Product> list = (Store) session.load(Store.class,storeId).getProductList();
Run Code Online (Sandbox Code Playgroud)

将帖子

...添加几个有用的指针(感谢Pascal)

14.3关联和连接

14.4连接语法的形式