子表的Id的Hibernate顺序

时间:2014-05-13 12:08:05

标签: mysql hibernate hql

我有两张表如下: // TmCategory表

public class TmCategory implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

@Column(name="CATEGORY_NAME")
private String categoryName;

@Column(name="OWNER_ID")
private BigInteger ownerId;

//bi-directional many-to-one association to TmCategoryRate
@OneToMany(mappedBy="tmCategory", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@javax.persistence.OrderBy("startDate ASC")
private Set<TmCategoryRate> tmCategoryRates;
//getters and setters

 }

// TmCategoryRates表

@Entity
@Table(name="tm_category_rates")
public class TmCategoryRate implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

@Column(name="CREATED_BY")
private BigInteger createdBy;

@Column(name="CREATED_DATE")
private Timestamp createdDate;

@Column(name="END_DATE")
private Timestamp endDate;

@Column(name="RATE")
private Double rate;

@Column(name="RATE_TYPE")
private String rateType;

@Column(name="START_DATE")
private Timestamp startDate;

//bi-directional many-to-one association to TmCategory
@ManyToOne
@JoinColumn(name="CATEGORY_ID")
private TmCategory tmCategory;
 //getters and setters.....

 }

以下是用于获取类别的分离标准

        DetachedCriteria criteria = DetachedCriteria.forClass(TmCategory.class);
        criteria.add(Restrictions.eq("id", catId));
        DetachedCriteria criteria1 =criteria.createCriteria("tmCategoryRates");
        criteria1.addOrder(Order.asc("id"));
        List<TmCategory> categories = getHibernateTemplate().findByCriteria(criteria);

这里我试图按照ID的升序对tmCategoryRates进行排序。 如果此类别至少有一个tmCategoryRates,我可以获得类别。如果没有可用的tmCategoryRates,则返回null而不是使用tmCategoryRates返回类别。

1 个答案:

答案 0 :(得分:0)

如果该类别可能没有费率,则需要左连接。目前尚不清楚为什么你在这里使用DetachedCriteria,但是从Hibernate docs看这个例子

    List cats = session.createCriteria( Cat.class )
        .createAlias("mate", "mt",
             Criteria.LEFT_JOIN,Restrictions.like("mt.name", "good%") )
                   .addOrder(Order.asc("mt.age"))
                   .list();

Hibernate 3.5 -- 16.4 Associations