我定义了以下实体: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;
}
但它什么都不返回,总是空的。我怎么解决它?
答案 0 :(得分:0)
试试这个: “选择*来自文章,Mgasin,其中Article.mgasin.id =”+ magasin.getId();
答案 1 :(得分:0)
我不知道你的magasin id的类型,所以请调整下面的代码。
首先获取id:
的Magasin实例Magasin mag = (Magasin)session.get(Magasin.class, id);
接下来,您可以通过访问者
访问magasin mag的文章Set<Article> articles = mag.getArticle();