Mybatis
Mybatis重点在与mapper.xml数据的绑定
1、参数绑定
- 1、一个参数
void selectUserById(Integer id);
<select id="selectUserById" resultType="entity.User">
select user_id as userId,user_name as username,password from t_user
where user_id = #{a}
</select>
其中#{a} a是mapper接口方法中的形参
- 多个参数
void selectUserByNameAndPassword(@param("username")String username,@param("password") String password);
<select id="selectUserByNameAndPassword" resultType="com.baizhi.entity.User">
select user_id as userId,user_name as username,password from t_user
where user_name = #{username} and password = #{password}
</select>
- 对象参数
void updateUser(User u);
<update id="updateUser">
update t_user
<set>
<if test="username != null">
user_name = #{username},
</if>
<if test="password != null">
password = #{password}
</if>
</set>
where user_id = #{userId}
</update>
username password userId 对应Use对象的成员属性,命名一致
当表中列名和对象属性名不一致时,需要用别名 或 resultMap
<select id="selectUsers" resultType="entity.User">
select user_id as userId,user_name as username,password from t_user
</select>
<resultMap id="user" type="entity.User">
<id column="user_id" property="userId">
<result column="user_name" property="username">
<result column="password" property="password">
</resultMap>
<select id="selectUsers" resultMap="user">
select *from t_user
</select>
- 一对一的关系
<resultMap id="user" type="entity.User">
<id column="user_id" property="userId">
<result column="user_name" property="username">
<result column="password" property="password">
<association property="复杂对象类型属性" javaType=""entity.Xxx>
<id column="Xxx_id" property="XxxId">
<result column="Xxx_name" property="XxxName">
</association>
</resultMap>
- 一对多关系
<resultMap id="user" type="entity.User">
<id column="user_id" property="userId">
<result column="user_name" property="username">
<result column="password" property="password">
<collection property="复杂对象类型属性" ofType=""entity.Xxx>
<id column="Xxx_id" property="XxxId">
<result column="Xxx_name" property="XxxName">
</collection>
</resultMap>
- 多对多关系
<resultMap type="com.baizhi.entity.Student"
id="studentResultMap">
<id column="student_id" property="studentId"/>
<result column="student_name" property="studentName"/>
<collection javaType="java.util.List"
ofType="com.baizhi.entity.Course" property="courses">
<id column="course_id" property="courseId"/>
<result column="course_name" property="courseName"/>
</collection>
</resultMap>
绑定数据的两种方式
-
#{}
底层使用占位符?绑定数据 -
${}
底层使用字符串拼接绑定数据,使用时必须使用注解@param绑定数据
动态sql -
<if test="">
-
<where>
去掉多余的and或or 代替sql中的where -
<set>
去掉多余的, 代替sql中的set
缓存 -
一级缓存
范围:同一个SqlSession连接中,也就是同一个事务中 -
二级缓存
范围:同一个namespace中,也就是同一个表中的增删改