如何使用WHERE子句选择多表

时间:2017-08-13 09:38:45

标签: java hibernate

我想得到用户名和用户名,mhId =“AAA”(mhId是表User_MonHoc中的一列。在User_MonHoc中,mhid + user_id是主键)。

表用户:

<hibernate-mapping>
<class name="entites.User" table="user" catalog="bthibernate" optimistic-lock="version">
    <id name="username" type="string">
        <column name="username" length="100" />
        <generator class="assigned" />
    </id>
    <property name="password" type="string">
        <column name="password" length="100" not-null="true" />
    </property>
    <property name="note" type="byte">
        <column name="note" not-null="true" />
    </property>
    <property name="name" type="string">
        <column name="name" length="100" not-null="true" />
    </property>
    <set name="userMonhocs" table="user_monhoc" inverse="true" lazy="true" fetch="select">
        <key>
            <column name="user_id" length="100" not-null="true" />
        </key>
        <one-to-many class="entites.UserMonhoc" />
    </set>
</class>

表User_MonHoc

<hibernate-mapping>
<class name="entites.UserMonhoc" table="user_monhoc" catalog="bthibernate" optimistic-lock="version">
    <composite-id name="id" class="entites.UserMonhocId">
        <key-property name="userId" type="string">
            <column name="user_id" length="100" />
        </key-property>
        <key-property name="mhId" type="string">
            <column name="mh_id" length="100" />
        </key-property>
    </composite-id>
    <many-to-one name="monhoc" class="entites.Monhoc" update="false" insert="false" fetch="select">
        <column name="mh_id" length="100" not-null="true" />
    </many-to-one>
    <many-to-one name="user" class="entites.User" update="false" insert="false" fetch="select">
        <column name="user_id" length="100" not-null="true" />
    </many-to-one>
    <property name="thoigianDk" type="timestamp">
        <column name="thoigian_dk" length="19" not-null="true" />
    </property>
</class>

我想得到用户名和用户名,mhId =“AAA”(mhId是表User_MH中的一列)。 谢谢!

1 个答案:

答案 0 :(得分:0)

您应该在SQL或HQL查询中加入User和User_MH表。在查询中将别名设置为User_MH o访问where子句中的User_MH表:

SQL:

SELECT tbl_user.useranme,tbl_user_mh.user_id FROM User AS tbl_user
INNER JOIN User_MH AS tbl_user_mh ON tbl_user.id=tbl_user_mh.user_id
WHERE tbl_user_mh.mhdl = 'AAA