mybatis 一对多关系

时间:2023-03-08 17:07:03
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.witwicky.mapper.UserMap"> <insert id="insertUser" parameterType="com.witwicky.pojo.User">
<!-- 将自动生成的编号放入user对象中的id属性中 -->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select
LAST_INSERT_ID()
</selectKey>
insert into user (username, sex, birthday, address)
values
(#{username}, #{sex}, #{birthday}, #{address})
</insert> <delete id="deleteUserById" parameterType="java.lang.Integer">
delete from user where
id = #{id}
</delete> <update id="updateUser" parameterType="com.witwicky.pojo.User">
update user set name=
#{name} where id=#{id}
</update> <select id="selectAllUser" resultType="com.witwicky.pojo.User">
select * from user
</select> <select id="selectUserByUserName" parameterType="java.lang.String"
resultType="com.witwicky.pojo.User"> <!-- List<User> list = sqlSession.selectList("test.selectUserByUserName",
"张"); -->
select * from user where username like '%${value}%' <!-- List<User> list = sqlSession.selectList("test.selectUserByUserName",
"%张%"); -->
<!-- select * from user where name like #{name} -->
</select> <!-- 查询订单信息,包含用户信息 -->
<resultMap type="com.witwicky.pojo.Orders" id="findOrdersResultMap">
<id property="id" column="order_id" />
<result property="userId" column="user_id" />
<result property="number" column="number" />
<result property="createtime" column="createtime" />
<result property="note" column="note" /> <association property="user" javaType="com.witwicky.pojo.User">
<id property="id" column="id" />
<result property="username" column="username" />
<result property="sex" column="sex" />
<result property="birthday" column="birthday" />
<result property="address" column="address" />
</association>
</resultMap>
<select id="findOrders" resultMap="findOrdersResultMap">
select u.*, o.id as order_id,
o.user_id, o.number, o.createtime, o.note from user as u, orders as o
where u.id = o.user_id
</select> <!-- 查询用户信息,包含订单 -->
<resultMap type="com.witwicky.pojo.User" id="findUserContainOrdersResultMap">
<id property="id" column="id" />
<result property="username" column="username" />
<result property="sex" column="sex" />
<result property="birthday" column="birthday" />
<result property="address" column="address" /> <collection property="orders" ofType="com.witwicky.pojo.Orders">
<id property="id" column="order_id" />
<result property="userId" column="user_id" />
<result property="number" column="number" />
<result property="createtime" column="createtime" />
<result property="note" column="note" />
</collection>
</resultMap>
<select id="findUserContainOrders" resultMap="findUserContainOrdersResultMap">
select u.*, o.id as
order_id,
o.user_id, o.number, o.createtime, o.note from user as u,
orders as o
where u.id = o.user_id
</select> </mapper>