我在下面有实体以及两者之间的@ManyToMany
映射。
@Entity
@Table(name = "user")
public class User implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 5340562707217344212L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
private String userName;
private String password;
private String firstName;
private String lastName;
private String emailId;
private Date createdDate;
private Byte status;
private Date lastModifiedDate;
@ManyToMany
@JoinTable(name = "user_products_mapper",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "product_id")
)
private List<Products> products = new ArrayList<Products>();
public void addProducts(Products product){
this.products.add(product);
}
@Entity
@Table(name="products")
public class Products implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1895580713896126954L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long productId;
private String productName;
private String description;
private double minBalance;
public Long getProductId() {
return this.productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
我的问题是:
1)如何获取基于user id
的产品?是指选择给定user id
订阅的所有产品?
2)我正在为此而苦苦挣扎,因为我在Product
端没有任何映射,但在User
端却没有任何映射。这是unidirectional association
3)我如何遍历Products
到User entity
?
答案 0 :(得分:0)
尝试这个。我相信这应该可行。
String hql = "select u.products from User u where u.id =:uid";
List<Object> products = sf.getCurrentSession().createQuery(hql)
.setParameter("uid", user_id)
.list();
System.out.println("products are :: " + products );