[英]Retrieve data using hsql - relation many to one
I define the following entities : BaseEntity
, magasin
and article
: 我定义以下实体: 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);
}
} }
How can create a hql query in order to retrieve all Article
for a magasin
selected ? 如何创建hql查询以检索所选magasin
所有Article
?
I try this 我尝试这个
@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;
}
But it returns nothing , always null .How can I resolve it ? 但是它什么也没有返回,总是为null。如何解决?
尝试以下操作:“选择* From Article,Mgasin,其中Article.mgasin.id =“ + magasin.getId();
I don't know the type of your magasin id so adapt the code below. 我不知道您的magasin ID的类型,因此请修改以下代码。
First get the Magasin instance for the id: 首先获取Magasin实例作为ID:
Magasin mag = (Magasin)session.get(Magasin.class, id);
Next you can access the articles for the magasin mag via accessor 接下来,您可以通过访问器访问magasin mag的文章
Set<Article> articles = mag.getArticle();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.