Hibernate:根据年龄排序对象

时间:2016-04-18 16:00:50

标签: java hibernate datetime

我有2个Hibernate实体:KennelDog

我想写一个方法来确定"最老的"我的数据库中的Kennel 是。

如果Kennel实体有一个"创建"这将是微不足道的。或类似的列,但它

但是,在我的Dog实体中,有born字段(DateTime)映射到BORN column

使用此Dog字段我想通过定义最老的Kennel ,其中包含最老的狗

狗窝里可以养很多只狗但狗只能养一只狗窝。

我该怎么做?

实体:

养犬:

@Entity
@Table(name = "KENNEL")
public class Kennel
{
    @Id
    private String id;

    @Column(name = "LOCATION")
    private String location;

}

犬:

@Entity
@Table(name = "DOG")
public class Dog
{
    @Id
    private String id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "BORN")
    private DateTime created;

    @Column(name= "KENNEL_ID)
    private String kennelId;        

   @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "KENNEL_ID")
    private Kennel kennel;

}

2 个答案:

答案 0 :(得分:1)

为什么不找到最老的狗,就像你说的那样琐碎,然后使用dog.kennel获得狗窝?

答案 1 :(得分:1)

尝试实施@Mark的建议。

Dog类中创建一个命名查询,如下所示,并从您的DAO中调用它。

@Entity
@Table(name = "DOG")
@NamedQueries({
   @NamedQuery(name="Dog.findOldestKennel", query="SELECT d.kennel 
       FROM Dog d order by d.created ASC LIMIT 1"),
   @NamedQuery(name="Dog.getAllKennelsInAgeOrder", query="SELECT d.kennel 
       FROM Dog d order by d.created ASC")
})
public class Dog {
    @Id
    private String id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "BORN")
    private DateTime created;

    @Column(name= "KENNEL_ID)
    private String kennelId;        

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "KENNEL_ID")
    private Kennel kennel;

}

使用Hibernate entityManager的示例DAO方法如下所示(您的项目实现可能不同),以便按照您所说的顺序获取所有kennel。在这里,我们调用在Dog类中创建的命名查询并返回结果列表。

public List<Kennel> getAllKennels(){
   try{
        // name of the desired NamedQuery to run should be given 
        Query queryStr = this.entityManager
            .createNamedQuery("Dog.getAllKennelsInAgeOrder");             
        List<Kennel> kennels =  queryStr.getResultList();

        if(null != kennels && !kennels.isEmpty()){
            return kennels;
        } else {
            return Collections.emptyList();
        }
    } catch (Exception e) {
        LOGGER.error("Exception Occcured in getAllKennels ", e);
    }
}