Mybatis

关于Maven项目

maven项目配置,解决静态资源被过滤

	<!--解决maven静态资源过滤问题,配置文件无法导出到代码编译路径使用-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <!--设置哪些文件-->
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

Mybatis运行过程

加载配置

在这里插入图片描述

获取SqlSession

在这里插入图片描述

使用Mapper

在这里插入图片描述

Mybatis配置

<!--子标签有特定的顺序-->
<configuration>
    <properties resource="database.properties"/>

配置相关的设置

    <settings>
        <!--设置日志实现-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>

        <!--驼峰命名映射,java对象的属性到数据库属性的映射-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>

        <!--开启全局缓存,默认开启-->
        <setting name="cacheEnabled" value="true"/>
    </settings>

别名

    <typeAliases>
        <!--指定别名,减少冗余的全限定类使用-->
        <typeAlias type="com.o11eH.bean.User" alias="user1"/>

        <!--指定包中类别名,以类名小写作为别名-->
        <package name="com.o11eH.bean"/>
    </typeAliases>

环境

    <!--可以配置多套环境,default为使用的环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}?useSSL=false"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

映射器

    <!--
    mapper的xml文件需要在配置文件中注册,resource的值为路径
    注册映射器方式还有:mapper标签class属性、package标签(使用全限定类名),要求xml配置文件与对应的接口同名
    -->
    <mappers>
        <package name="com.o11eH.dao"/>
    </mappers>

</configuration>

Mapper配置

Mapper相关实体、接口
@Alias("user2")//包名方式设置别名时,可以修改别名
//缓存的使用需要使用序列化
public class User implements Serializable {
    private Integer id;
    private String name;
    private String password;
    private BigDecimal balance;
    private boolean isAdmin;
public interface UserMapper {
    List<User> selectUsers();

    User selectUserById(int id);

    /*
    注解完成映射,对于复杂语句不建议使用,
    例如,实体类属性和数据库表属性名不一致时,需要使用别名等
    基本数据类型的参数需要加上@param注解
    SQL语句使用的参数@Param中的参数
    */
    @Select("select id,`name`,is_admin as isAdmin from user where `name`= #{username}")
    User selectUserByName(@Param("username") String name);

    List<User> selectUserLimit(Map<String, Integer> map);

    int insert(User user);

    int update(User user);

    int delete(int id);
}
基本配置
	<!--命名空间为对应的接口-->
	<mapper namespace="com.o11eH.dao.UserMapper">

	<!--实体类的属性、与数据库中属性名字不一致,resultMap可以做到属性间映射,type为对应的实体类-->
    <resultMap id="userMap" type="user1">
        <result property="isAdmin" column="is_admin"/>
    </resultMap>

    <!--id为接口声明方法,以映射SQL语句,resultMap为结果映射-->
    <select id="selectUsers" resultMap="userMap">
        select *
        from mybatis.user;
    </select>
特殊配置
多对一
按照查询嵌套处理
	<resultMap id="studentResultMap1" type="student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>

        <!--按照查询嵌套处理-->
        <association property="teacher" javaType="teacher" column="tid" select="selectTeacherById"/>
    </resultMap>
    <select id="selectStudents1" resultMap="studentResultMap1">
        select *
        from mybatis.student
    </select>

    <!--子查询-->
    <select id="selectTeacherById" resultType="teacher">
        select *
        from mybatis.teacher
        where id = #{tid}
    </select>
按照结果嵌套处理
    <resultMap id="studentResultMap2" type="student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>

        <!--按照结果嵌套处理-->
        <association property="teacher" javaType="teacher" column="tname">
            <!--student、teacher表中name属性相同,SQL语句需要起别名-->
            <result property="id" column="tid"/>
            <result property="name" column="tname"/>
        </association>
    </resultMap>
    <select id="selectStudents2" resultMap="studentResultMap2">
        select s.id,
               s.name,
               s.tid,
               t.name tname
        from mybatis.student s,
             mybatis.teacher t
        where s.`tid` = t.`id`;
    </select>
一对多
    <resultMap id="teacherResultMap2" type="teacher">
        <result property="id" column="id"/>

        <!--JavaTyp即对象属性(List集合),ofType为集合中元素的类型-->
        <collection property="students" javaType="ArrayList" ofType="student" column="id" select="selectStudentById"/>
    </resultMap>
    <select id="selectTeachers2" resultMap="teacherResultMap2">
        select *
        from mybatis.teacher
    </select>
按照结果嵌套处理
<resultMap id="teacherResultMap1" type="teacher">
        <result property="id" column="id"/>
        <result property="name" column="name"/>

        <!--ofType为集合元素的类型-->
        <collection property="students" ofType="student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
        </collection>
    </resultMap>
    <select id="selectTeachers1" resultMap="teacherResultMap1">
        select t.id, t.name, s.id sid, s.name sname
        from mybatis.teacher t,
             mybatis.student s
        where t.id = s.tid
    </select>

动态SQL

常用标签是if标签

where标签
    <!--动态SQL,不同的查询条件,将生成不同的SQL语句-->
    <select id="selectArticles2" parameterType="map" resultType="article">
        select * from mybatis.article
        /*可能有多个查询条件,需要加上 and 关键字,保证SQL语句正确*/
        <where>
            /*引用SQL片段*/
            <include refid="selectWhereIf"/>
        </where>
    </select>
<!--SQL片段-->
    <sql id="selectWhereIf">
        <if test="id!=null">
            id=#{id}
        </if>
        <if test="title!=null">
            and title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
        <if test="createTime!=null">
            and createTime=#{createTime}
        </if>
        <if test="views!=null">
            and views=#{views}
        </if>
    </sql>
set标签
    <update id="updateById" parameterType="map">
        update mybatis.article
        /*可能修改多个记录的属性值,需要加上逗号,保证SQL语句正确*/
        <set>
            <if test="title!=null">
                title=#{title},
            </if>
            <if test="author!=null">
                author=#{author},
            </if>
            <if test="createTime!=null">
                createTime=#{createTime},
            </if>
            <if test="views!=null">
                views=#{views}
            </if>
        </set>
        where id=#{id}
    </update>
foreach标签
    <select id="selectArticlesByAuthors" resultType="article">
        select *
        from mybatis.article

        <where>
            <foreach open="author in (" close=")" separator="," collection="authors" item="author">
                #{author}
            </foreach>
        </where>

    </select>
缓存
<!--
    启动全局二级缓存
    eviction="FIFO"
    flushInterval="60000"
    size="512"
    readOnly:true,只读的缓存会给所有调用者返回缓存对象的相同实例;false,可读写的缓存会(通过序列化)返回缓存对象的拷贝
    -->
    <cache readOnly="true"/>

参考

【狂神说Java】Mybatis最新完整教程IDEA版通俗易懂
狂神说MyBatis01:第一个程序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值