在Hibernate查询中减去?

时间:2013-08-14 08:53:35

标签: java sql hibernate one-to-many

我想实现一个查询,该查询选择只有填充此条件的子项的所有父项 children.date = today 。目标是提高性能,我不需要其他日子。

Query q = ss.createQuery("select p from Parent p where exists( from p.children c where    c.date = :now)");
     q.setTimestamp("now", new DateTime().minusDays(1).toDate());
     qc=q.list();

另一种方式:

DateMidnight first = new DateMidnight(); //today at 00h00 00min 00 JodaTime
  ss.createCriteria(Parent.class)
      .createAlias("children", "c")
      .add(Restrictions.between("c.date",first.toDate(), first.plus(14400000).toDate()))
      .list();

父类

@Entity
public class Parent implements Serializable {

private static final long serialVersionUID = 1L;
  @Id
  @GeneratedValue(strategy=GenerationType.TABLE)
  private Integer id;

  @OneToMany( cascade = {CascadeType.ALL},mappedBy = "parentId",fetch = FetchType.LAZY)
  @Column(name="id_parent",nullable=true,unique = true)
  @Cascade(value={org.hibernate.annotations.CascadeType.ALL,org.hibernate.annotations.CascadeType.SAVE_UPDATE,org.hibernate.annotations.CascadeType.DELETE,org.hibernate.annotations.CascadeType.REMOVE})
  private List<Child> children=new ArrayList<Child>();

和Child.class

@Entity
public class Child implements Serializable{

private static final long serialVersionUID = 1L;
 @Id
@GeneratedValue(strategy=GenerationType.TABLE)
 @Column(name = "childID", unique = true, nullable = false)
private long childId1;

private Date date;

private String childId2;

2 个答案:

答案 0 :(得分:0)

如果该字段是时间戳日期和时间,请更改您的查询,以便查询应该为您提供所需数据的所有数据(日期00:00:00和日期23:59:59)

答案 1 :(得分:0)

在这种情况下,我会使用带有Hibernate过滤器的HQL命名查询。 http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/filters.html

父代码将变为如下:

  @OneToMany( cascade = {CascadeType.ALL},mappedBy = "parentId",fetch = FetchType.LAZY)
  [...]
  @Filter(name = "todayChildrenOnly", condition = "date = :now")
  private List<Child> children=new ArrayList<Child>();

以上内容将在SQL连接条件以及外键检查(join ... on ...)中进行转换。 如果“date”是子表的索引,那么你应该获得更好的表现。