mybatis的深入和多表
1.mybatis的连接池
mybatis连接池使用以及分析:
1.连接池:我们在实际引用开发中都会使用连接池,因为他可以减少我们获取连接需要的时间
2.mybatis中的连接池:
配置的位置:主配置SqlMapConfig.xml中DataSource标签的type属性,就是表示连接池
Type属性取值:
POOLED:采用传统javax.sql.datasource规范中的连接池方式
UNPOOLED:采用传统javax.sql.datasource连接方式,没有使用连接池
JNDI:采用服务器提供的JNDI技术实现,来获取datasource对象,不同服务器拿到的DataSource是不一样的,如果不是web或者maven的war工程是不能使用的
事务
mybatis的事务是通过sqlsession对象的commit方法和rollback方法实现的事务的提交个回滚
2.mybatis中基于XML配置的动态SQL语句使用
mappers配置中的几个标签:
<if/>标签
条件查询的时候可以使用
<!-- 查询条件 -->
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
select * from user where 1=1
<if test="userName != null">
and username like #{userName}
</if>
<if test="userSex != null">
and sex = #{userSex}
</if>
</select>
<where/>标签
可以让上面的where 1=1去除
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
select * from user
<where>
<if test="userName != null">
and username like #{userName}
</if>
<if test="userSex != null">
and sex = #{userSex}
</if>
</where>
</select>
<foreach/>标签
子查询使用,如:select * from user where id in(41,42,43,46)
<select id="findUserByIds" resultMap="userMap" parameterType="queryVo">
select * from user
<where>
<if test="ids != null and ids.size() > 0">
<foreach collection="ids" open="and id in(" close=")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>
<sql/>标签
封装重复的SQL语句
<!-- 封装SQL语句 -->
<sql id="defaultUser">
select * from user
</sql>
<!-- 查询所有 -->
<select id="findAll" resultMap="userMap">
<include refid="defaultUser"></include>
</select>
3.mybatis的多表查询
**一对一:association ** 从表实体包含一个对主表实体的引用
<resultMap id="accountUserMap" type="account">
<id property="id" column="aid"></id>
<result property="uid" column="id"></result>
<result property="money" column="money"></result>
<!-- 一对一关系映射 -->
<association property="user" column="uid" javaType="user">
<id property="userId" column="id"></id>
<result property="userName" column="username"></result>
<result property="userBirthday" column="Birthday"></result>
<result property="userSex" column="sex"></result>
<result property="userAddress" column="Address"></result>
</association>
</resultMap>
<select id="findAll" resultMap="accountUserMap">
select u.*,a.ID as aid,a.MONEY from account as a,user as u where a.UID = u.id
</select>
一对多:collection 主表实体应该包含从表实体的集合引用
<!-- 数据库列名和实体名对不上 使用mapper解决 -->
<resultMap id="userMap" type="user">
<id property="userId" column="id"></id>
<result property="userName" column="username"></result>
<result property="userBirthday" column="birthday"></result>
<result property="userSex" column="sex"></result>
<result property="userAddress" column="address"></result>
<!-- 设置一对多的关系 property属性名称,ofType映射类型,account是别名 -->
<collection property="accounts" ofType="account">
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
</collection>
</resultMap>