【发布时间】:2011-04-21 17:25:27
【问题描述】:
我是 hibernate 初学者,在尝试使用 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;
等等。
这是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;
等等。
这是输出:(产品 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
我有 2 个额外的类,ProductDAO 和 StoreDAO 负责查询,除了表名/类名之外,这两个类中的代码都相似。
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;
}
}
有没有办法只用hibernate解决这个问题?
谢谢
【问题讨论】:
-
如何检索产品列表?你用什么?加载?得到?休眠标准?高品质? SQL?
-
我有 2 个额外的类,ProductDAO 和 StoreDAO 负责查询,除了表名之外,这两个类中的代码都相似。 public class ProductDAO { public static List
getStoreProductsList() { Session hibernateSession = HibernateUtil.getSession(); hibernateSession.beginTransaction();查询查询 = hibernateSession.createQuery("来自 se.kyh.stores.entities.Product"); hibernateSession.getTransaction().commit();列表 storeProducts = query.list();退货商店产品; } -
您应该将此评论添加到原始问题中。只需尝试编辑问题。