Mybatis连接池丶动态sql丶抽取sql语句

当实体类的属性(uid)与数据库的字段(id)不一致的时候

对于增删改: 只需在传入参数后的占位符中把对应的属性传递进去就行
对于查询:
        1. 可以通过数据库的别名来解决 select id as uid from user
        2. 可以使用resultMap来设置
            <resultMap id="userMap" type="com.qin.domain.User(或者别名)">
                <id property = "uid" column="id"/>            
                <result property = "username" column="username"/>    
            </resultMap>
            id 标签:用于指定主键字段
            result 标签:用于指定非主键字段
            column 属性:用于指定数据库列名
            property 属性:用于指定实体类属性名称

* 当实体类的属性与表的字段不一致的时候才使用resultMap,一样的时候使用resultType            

Mybatis中的连接池

1. Mybatis中的连接池提供了3种方式的配置
    配置的位置:
        主配置文件SqlMapConfug.xml中的dataSource标签,type属性就是表示采用何种
        连接池方式
    type属性的取值:
        POOLED:   采用传统的javax.sql.DataSource规范中的连接池,mybatis中有针对规范的实现
        UNPOOLED: 采用传统的获取连接的方式,虽然也是使用javax.sql.DataSource规范中的连接池,但是并没有
                    每次都是创建一个新的连接.
        JDNI:        java naming and directory interface
                    使用的是服务器中提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到的对象不同
                    注意:不是web或者maven工厂是不可以使用的

事务性

设置自动提交: session = factory.openSession(true);

动态sql语句

if
    <select id="findByUser" resultType="user" parameterType="user">
    select * from user where 1=1
    <if test="username!=null and username != '' ">
    and username like #{username}
    </if>
    <if test="address != null">
    and address like #{address}
    </if>
    </select>

    注意:<if>标签的 test 属性中写的是对象的属性名,如果是包装类的对象要使用 OGNL 表达式的写法。
where 
    替换 where 1 = 1 并去掉第一个and
foreach
    <select id="findInIds" resultType="user" parameterType="queryvo">
        select * from user
    <where>
    <if test="ids != null and ids.size() > 0">
    <foreach collection="ids" open="id in ( " close=")" item="uid"
    separator=",">
    #{uid}
    </foreach>
    </if>
    </where>
    </select>

    <foreach>标签用于遍历集合,它的属性:
        collection:代表要遍历的集合元素,注意编写时不要写#{}
        open:代表语句的开始部分
        close:代表结束部分
        item:代表遍历集合的每一个元素,生成的变量名
        separator:代表分隔符

trim(多用于insert) 与set(多用于update中的多个条件的,)

Mybatis简化sql片段(抽取sql语句)

* 抽取重复的语句代码片段 
    <sql id="defaultSql">
    select * from user
    </sql>

* 引用代码片段
    <include refid="defaultSql"></include>

猜你喜欢

转载自blog.csdn.net/qq_35472880/article/details/83245572