我定义以下实体:BaseEntity
,magasin
和article
:
@Entity(name = "magasin")
@Table(name = "magasin")
public class Magasin extends BaseEntity {
private static final long serialVersionUID = 1L;
@Basic
@Size(min=5, max=100, message="The name must be between {min} and {max} characters")
private String name;
@OneToMany(cascade=CascadeType.ALL, mappedBy="magasin")
@Valid
private Set<Article> article;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Article> getArticle() {
return article;
}
public void setArticle(Set<Article> article) {
this.article = article;
}
}
@Entity(name="article")
@Table(name="article")
public class Article extends BaseEntity {
private static final long serialVersionUID = 1L;
@ManyToOne
private Magasin magasin;
@Basic
@Size(min=5, max=100, message="The name must be between {min} and {max} characters")
private String name;
@Basic
private float price;
public Magasin getMagasin() {
return magasin;
}
public void setMagasin(Magasin magasin) {
this.magasin = magasin;
}
public String getName() {
return name;
}
public void setName(String nom) {
this.name = nom;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
@MappedSuperclass
public class BaseEntity {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public boolean isNew() {
return (this.id == null);
}
}
如何创建hql查询以便为选定的
Article
检索所有magasin
?我尝试这个
@Override
public List<Article> findArticle(Magasin magasin) {
String query = "From Article m where m.magasin.id = "+magasin.getId();
System.out.print(query);
Session session = getSessionFactory().getCurrentSession();
if((session.createQuery(query).list()!=null) && (session.createQuery(query).list().size()!=0))
return (List<Article>) session.createQuery(query).list();
else
return null;
}
但是它什么也没有返回,总是为null。如何解决?
最佳答案
我不知道您的magasin ID的类型,因此请修改以下代码。
首先获取Magasin实例作为ID:
Magasin mag = (Magasin)session.get(Magasin.class, id);
接下来,您可以通过访问器访问magasin mag的文章
Set<Article> articles = mag.getArticle();