Mybatis雜記:
當數據庫涉及到一對多時Mybatis的處理方法:
- 例如在bean中定義如下兩個類(Order 類和User類),用戶和訂單是一對多關係,1個用戶可能會有多個訂單,但是一個訂單隻屬於一個用戶。
此時你需要在那個1的地方定義一個集合,Set和List皆可!
public class Order {
private long id;
private String name;
private double price;
public User user;
//Getter and Setter
//toString
//Constuctor
}
public class User {
private long id;
private String name;
private Set<Order> orders;
//Getter and Setter
//toString
//Constuctor
}
- 扯到一點插入語句在Mybatis中的使用!例如在User表中插入數據時:
數據庫:Oracle
主鍵通過序列進行維護時,就可以用selectKey
來引入我們的主鍵。
order
中參數有兩種:
1.AFTER:在insert之後執行
2.BEFORE:在insert之前執行
keyProperty
:查詢到的結果(這裏即序列的值)將要賦給哪個列
resultType
:查詢到的結果的屬性(即keyProperty
中的屬性)
<insert id="saveUser" parameterType="user">
<selectKey order="BEFORE" keyProperty="id" resultType="long">
select u_seq.nextval from dual
</selectKey>
insert into s_user(id,name) values(#{id},#{name})
</insert>
- 做一些查詢的demo:
1.基於User的id去查詢所有的信息:
在Mapper接口中定義:User findUserAndOrders(long id);
Mapper.xml中:
同樣的套路,先定義一個order
的resultMap
:
<resultMap id="order_mod1" type="order">
<id property="id" column="ids"/>
<result property="name" column="names"/>
<result property="price" column="price"/>
</resultMap>
隨後定義User的resultMap:
一對一的時候用的是association
,這裏使用collection
來描述“多”的這個關係,另一方面,在bean中寫的也是個集合!
在collection
中,property
參數根據之前談過的規則(Mybatis會自動去搜尋getXX()方法,並將其以去掉get,並取後面字段小寫的方式來獲取屬性名),resultMap參數寫的是剛纔寫的id 爲order_mod1
的resultMap.
<resultMap id="user_mod1" type="user" >
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- 表示集合的封裝 property指向封裝對象中的集合引用變量,引用對象 -->
<collection property="orders" resultMap="order_mod1" />
</resultMap>
這樣的話 select
就可以這麼寫:
<select id="findUserAndOrders" parameterType="long" resultMap="user_mod1">
select s.id,s.NAME,d.id ids,d.name names,d.PRICE,d.USER_ID
from S_USER s, S_ORDER d
where s.ID = d.USER_ID and s.ID = #{id}
</select>
2.根據用戶的id去尋找所有的Order:
在Mapper中定義:Set<Order> selectOrderByUser_id(long id);
Mapper.xml中:
<select id="selectOrderByUser_id" parameterType="long" resultMap="order_mod1">
select id ids,name names,PRICE
from S_ORDER
where USER_ID = #{id}
</select>
3.查詢所有的用戶及訂單:
在Mapper接口中定義:List<User> selectUserandOrder();
Mapper.xml中:
在collection
中 select
中填寫的是剛纔2中的操作(根據用戶的id去尋找所有的Order),column
屬性又把user_Id
傳過去,查詢到的所有數據就會拼接在property
的屬性中,這樣就完成了查詢所有數據的能力!
<resultMap id="mod_user" type="user">
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- 基於當前查詢的用戶 id 去 order 表找訂單 -->
<collection property="orders" column="id" select="selectOrderByUser_id"/>
</resultMap>
select標籤:
<select id="selectUserandOrder" resultMap="mod_user">
select s.id,s.NAME,d.id ids,d.NAME names,d.PRICE,d.USER_ID
from S_USER s, S_ORDER d
where s.ID = d.USER_ID
</select>