i am a hibernate-beginner and have a problem when trying to join 2 tables with hibernate. What i am trying to do is get the list of products a certain store has depending on the store id, but what i am getting is the list of all available products in the database listed under every store.
Here’s the code for 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;
etc..
and here’s the code for 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;
etc..
Here’s the output: (products A should be under Butik A and products B under 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
I have 2 additional classes, ProductDAO and StoreDAO that take care of the query, the code is similar in both classes except the 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;
}
}
Is there any way of solving this with hibernate only?
Thanks
After going through your comment. It looks like you never set the condition there, of course then, you will end up getting all the products no matter which store they belong. No surprise. Where you specify the criteria?
You can do something like,
Or you can get the
Storeand then get the list ofProducts like below,Another and simpler way, as we know store_id is the primary key, (Thanks to Pakore for reminding me)
[Edited]
…to add a couple of useful pointers (Thanks to Pascal)