我有以下模型类:
@Entity
@Table(name = "title")
public final class Title extends ModelData<Title>
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer titleID;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "title")
private Set<Book> books;
}
@Entity
@Table(name = "book")
public final class Book extends ModelData<Book>
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "bookID")
private int bookID;
@ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
@JoinColumn(name = "titleID")
private Title title;
@Column(name = "edition")
private Integer edition;
@Column(name = "isbn")
private String ISBN;
}
我想写一个Criteria查询,它等同于以下SQL;
Select
t.title, b.edition
from
books b, title t
where
b.titleID = t.titleID
and
(b.edition=4 OR t.title LIKE '%Java%);
我尝试了以下内容:
Criteria c = session.createCriteria(Book.class);
Criteria titleCriteria = c.createCriteria("title");
titleCriteria.add(Restrictions.like("title", "%Java%");
Criterion edition = Restrictions.eq("edition", 4);
LogicalExpression orExp = Restrictions.or(edition, titleCriteria); //cannot do this
我如何实现上述目标?
感谢。
答案 0 :(得分:1)
public class MyDTO {
private String dtoTitle;
private String dtoEdition;
// + setters/getters
}
Criteria c = session.createCriteria(Book.class,"b");
c.createAlias("title", "t");
c.add(
Restrictions.disjunction()
.add( Restrictions.like("t.title", "%Java%") )
.add( Restrictions.eq("b.edition", 4) )
);
c.setProjection(
Projections.projectionList()
.add( Projections.property("t.title"), "dtoTitle" )
.add( Projections.property("b.edition"), "dtoEdition" )
);
c.setResultTransformer(Transformers.aliasToBean(MyDTO.class));
List<MyDTO> result = (List<MyDTO>)c.list();
这样的事应该可以正常工作。
在使用许多标准的dao上,你应该考虑使用静态导入。
答案 1 :(得分:1)
另一个想法
将yout标准转换为公式字段并评估为正常标准
将公式字段添加到映射文件或注释到类
<property name="titlename" type="string"
formula="(Select title.title from title
where title.titleID= titleID)"/>
然后
Criteria c = session.createCriteria(Book.class)
Criteria titleCriteria = c.createCriteria("title");
titleCriteria.add(Restrictions.like("titlename", "%Java%");
Criterion edition = Restrictions.eq("edition", 4);
LogicalExpression orExp = Restrictions.or(edition, titleCriteria); //CAN< do this!!!
答案 2 :(得分:0)
我想你想要这个。我没有测试过,所以可能会有一些小错误,但基本想法是正确的。
Criteria c = session.createCriteria(Book.class);
Criterion titleCriterion = Restrictions.like("title.title", "%Java%");
Criterion edition = Restrictions.eq("edition", 4);
c.add( Restrictions.or( edition, titleCriterion ));
答案 3 :(得分:0)
对于超过2个OR条件,它使用起来更具可读性:
c.add(
Restrictions.disjunction()
.add(Restrictions.eq(...))
.add(Restrictions.eq(...))
.add(Restrictions.eq(...))
)