使用hibernate Composite(key)Object的条件查询

时间:2011-02-21 08:13:20

标签: hibernate

CREATE TABLE ratecodes(   roomId int(11)NOT NULL DEFAULT'0',   date日期NOT NULL DEFAULT'0000-00-00', ...,PRIMARY KEY(roomIddate)) 的hbm.xml

<class catalog="hermes" name="com.hermes.data.RateCode" table="ratecodes">
<composite-id class="com.hermes.data.RateCodeId" name="id">
      <key-property name="roomId" type="int">
        <column name="roomId"/>
      </key-property>
      <key-property name="date" type="date">
        <column length="10" name="date"/>
      </key-property>
    </composite-id>
    <version name="version" type="java.lang.Long">
      <column name="version" precision="10" scale="0"/>
    </version>

我想查询 HibernateUtil.getCurrentSession()。createQuery(“from RateCode where(RatecodeId(between |&lt;)RateCodeId)”

SQL: “来自RateCode,其中roomId = 3000,日期&gt;:fromDate和date&lt;:toDate”

RatecodeId.java(复合)

public class RateCodeId implements java.io.Serializable {

    private int roomId;
    private Date date;

    public RateCodeId() {
    }

    public RateCodeId(int roomId, Date date) {
        this.roomId = roomId;
        this.date = date;
    }

    public int getRoomId() {
        return this.roomId;
    }

    public void setRoomId(int roomId) {
        this.roomId = roomId;
    }

    public Date getDate() {
        return this.date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public boolean equals(Object other) {
        if ((this == other)) {
            return true;
        }
        if ((other == null)) {
            return false;
        }
        if (!(other instanceof RateCodeId)) {
            return false;
        }
        RateCodeId castOther = (RateCodeId) other;

        return (this.getRoomId() == castOther.getRoomId())
                && ((this.getDate() == castOther.getDate()) || (this.getDate() != null && castOther.getDate() != null && this.getDate().equals(castOther.getDate())));
    }

    public int hashCode() {
        int result = 17;

        result = 37 * result + this.getRoomId();
        result = 37 * result + (getDate() == null ? 0 : this.getDate().hashCode());
        return result;
    }
}

如何在Object中设置FromDate和Todate并执行RateCodeID的条件

1 个答案:

答案 0 :(得分:4)

String hql = "from RateCode rc where rc.id.roomId = 3000"
             + " and rc.id.date > :fromDate"
             + " and rc.id.date < :toDate";
Query q = session.createQuery(hql);
q.setParameter("fromDate", theFromDate);
q.setParameter("toDate", theToDate);