我有两个表,如下所示:
// 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返回类别。

最佳答案

如果该类别可能没有价格,则需要左联接。目前尚不清楚为什么在这里使用DetachedCriteria,但请参阅Hibernate文档中的示例

    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

10-01 13:30