Mybatis 学习笔记

一、概念

        1. mybatis 是一个优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。

        2. mybatis通过xml或注解的方式将要执行的各种 statement配置起来,并通过java对象和statement中sql的动态参数进行映射生成最终执行的sql语句。

        3. 最后mybatis框架执行sql并将结果映射为java对象并返回。采用ORM思想解决了实体和数据库映射的问题,对jdbc 进行了封装,屏蔽了jdbc api 底层访问细节,使我们不用与jdbc api 打交道,就可以完成对数据库的持久化操作。

二、MyBatis开发步骤

        1. 添加MyBatis的坐标

        2. 创建user数据表

        3. 编写User实体类

        4. 编写映射文件UserMapper.xml

<?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="userMapper">
   <select id="findAll" resultType="com.itheima.domain.User">
        select * from User
   </select>
</mapper>

        5. 编写核心文件SqlMapConfig.xml

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN“ "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///test"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers> 
        <mapper resource="mapper/UserMapper.xml"/> 
    </mappers>
</configuration>

        6. 编写测试类

三、MyBatis的增删改查操作

        1. MyBatis的插入数据操作

                1. 编写UserMapper映射文件

<mapper namespace="userMapper">
    <insert id="add" parameterType="com.domain.User">
        insert into user values(#{id},#{username},#{password})
    </insert>
</mapper>

                 2. 编写插入实体User的代码

InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int insert = sqlSession.insert("userMapper.add", user);
System.out.println(insert);
//提交事务
sqlSession.commit();
sqlSession.close();

                3. 插入操作注意问题

                        1. 插入语句使用insert标签  

                        2. 在映射文件中使用parameterType属性指定要插入的数据类型

                        3. Sql语句中使用#{实体属性名}方式引用实体中的属性值

                        4. 插入操作使用的API是sqlSession.insert(“命名空间.id”,实体对象);

                        5. 插入操作涉及数据库数据变化,所以要使用sqlSession对象显示的提交事务,即sqlSession.commit()

        2. MyBatis的修改数据操作 

                1. 修改操作注意问题

                        1. 修改语句使用update标签  

                        2. 修改操作使用的API是sqlSession.update(“命名空间.id”,实体对象);

        3. MyBatis的删除数据操作

                1.  删除操作注意问题

                        1. 删除语句使用delete标签

                        2. Sql语句中使用#{任意字符串}方式引用传递的单个参数

                        3. 删除操作使用的API是sqlSession.delete(“命名空间.id”,Object);

四、MyBatis核心配置文件

        1.  MyBatis核心配置文件层级关系

                

        2. MyBatis常用配置

                1. environments标签

                数据库环境的配置,支持多环境配置

<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="${jdbc.driver}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </dataSource>
    </environment>
</environments>

                 其中,事务管理器(transactionManager)类型有两种:

                JDBC:这个配置就是直接使用了JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务作用域。

                MANAGED:这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。 默认情况下它会关闭连接,然而一些容器并不希望这样,因此需要将 closeConnection 属性设置为 false 来阻止它默认的关闭行为。

                 其中,数据源(dataSource)类型有三种:

                UNPOOLED:这个数据源的实现只是每次被请求时打开和关闭连接。

                POOLED:这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来。

                JNDI:这个数据源的实现是为了能在如 EJB 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的引用。

         2. mapper标签

                该标签的作用是加载映射的,加载方式有如下几种:

                        使用相对于类路径的资源引用,例如:<mapperresource="org/mybatis/builder/AuthorMapper.xml"/>

                        使用完全限定资源定位符(URL),例如:<mapper url="file:///var/mappers/AuthorMapper.xml"/>

                        使用映射器接口实现类的完全限定类名,例如:<mapper class="org.mybatis.builder.AuthorMapper"/>

                        将包内的映射器接口实现全部注册为映射器,例如:<package name="org.mybatis.builder"/>

        3. Properties标签

        实际开发中,习惯将数据源的配置信息单独抽取成一个properties文件,该标签可以加载额外配置的properties文件

        4. typeAliases标签

        类型别名是为Java 类型设置一个短的名字。

<typeAliases>
    <typeAlias type="com.domain.User“ alias="user"></typeAlias>
</typeAliases>




<select id="findAll" resultType=“user">
    select * from User
</select>

        5. typeHandlers标签

                1. 无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。

                下表描述了一些默认的类型处理器(截取部分)。

                 2. 你可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。

                        步骤:

                                ① 定义转换类继承类BaseTypeHandler<T>

                                ② 覆盖4个未实现的方法,其中setNonNullParameter为java程序设置数据到数据库的回调方法,getNullableResult为查询时 mysql的字符串类型转换成 java的Type类型的方法

                                ③ 在MyBatis核心配置文件中进行注册

                                ④ 测试转换是否正确

        6. plugins标签

        MyBatis可以使用第三方的插件来对功能进行扩展

五、MyBatis映射文件

1. 动态sql语句

        1. 动态 SQL  之<if>

        我们根据实体类的不同取值,使用不同的 SQL语句来进行查询。比如在 id如果不为空时可以根据id查询,如果username 不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到

<select id="findByCondition" parameterType="user" resultType="user">
    select * from User
    <where>
        <if test="id!=0">
            and id=#{id}
        </if>
        <if test="username!=null">
            and username=#{username}
        </if>
    </where>
</select>

        2. 动态 SQL  之<foreach>

        循环执行sql的拼接操作,例如:SELECT * FROM USER WHERE id IN (1,2,5)。

<select id="findByIds" parameterType="list" resultType="user">
    select * from User
    <where>
        <foreach collection="array" open="id in(" close=")" item="id" separator=",">
            #{id}
        </foreach>
    </where>
</select>

         foreach标签的属性含义如下:

        <foreach>标签用于遍历集合,它的属性:

                ① collection:代表要遍历的集合元素,注意编写时不要写#{}

                ② open:代表语句的开始部分

                ③ close:代表结束部分

                ④ item:代表遍历集合的每个元素,生成的变量名

                ⑤ sperator:代表分隔符

2. SQL片段抽取

        Sql 中可将重复的 sql 提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的

<!--抽取sql片段简化编写-->
<sql id="selectUser"> select * from User</sql>
<select id="findById" parameterType="int" resultType="user">
    <include refid="selectUser"></include> where id=#{id}
</select>
<select id="findByIds" parameterType="list" resultType="user">
    <include refid="selectUser"></include>
    <where>
        <foreach collection="array" open="id in(" close=")" item="id" separator=",">
            #{id}
        </foreach>
    </where>
</select>

六、Mybatis多表查询

        1 一对一配置:使用<resultMap>做配置

<mapper namespace="com.mapper.OrderMapper">
    <resultMap id="orderMap" type="com.domain.Order">
        <result column="uid" property="user.id"></result>
        <result column="username" property="user.username"></result>
        <result column="password" property="user.password"></result>
        <result column="birthday" property="user.birthday"></result>
    </resultMap>
    <select id="findAll" resultMap="orderMap">
        select * from orders o,user u where o.uid=u.id
    </select>
</mapper>

        2. 一对多配置:使用<resultMap>+<collection>做配置

<mapper namespace="com.mapper.UserMapper">
    <resultMap id="userMap" type="com.domain.User">
        <result column="id" property="id"></result>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="birthday" property="birthday"></result>
        <collection property="orderList" ofType="com.itheima.domain.Order">
            <result column="oid" property="id"></result>
            <result column="ordertime" property="ordertime"></result>
            <result column="total" property="total"></result>
        </collection>
    </resultMap>
    <select id="findAll" resultMap="userMap">
        select *,o.id oid from user u left join orders o on u.id=o.uid
    </select>
</mapper>

        3. 多对多配置:使用<resultMap>+<collection>做配置

<resultMap id="userRoleMap" type="com.domain.User">
    <result column="id" property="id"></result>
    <result column="username" property="username"></result>
    <result column="password" property="password"></result>
    <result column="birthday" property="birthday"></result>
    <collection property="roleList" ofType="com.domain.Role">
        <result column="rid" property="id"></result>
        <result column="rolename" property="rolename"></result>
    </collection></resultMap>
<select id="findAllUserAndRole" resultMap="userRoleMap"> 
   select u.*,r.*,r.id rid from user u left join user_role ur on u.id=ur.user_id
    inner join role r on ur.role_id=r.id
</select>

七、Mybatis的Dao层实现

        1. 代理开发方式

        Mapper 接口开发方法只需要程序员编写Mapper 接口(相当于Dao 接口),由Mybatis 框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。

                1. Mapper 接口开发需要遵循以下规范:

                        1、 Mapper.xml文件中的namespace与mapper接口的全限定名相同

                        2、 Mapper接口方法名和Mapper.xml中定义的每个statement的id相同

                        3、 Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同

                        4、 Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同

public interface UserMapper {
    User findById(int id);
}
<mapper namespace="com.mapper.UserMapper">
    <select id="findById" parameterType="int" resultType="user">
        select * from User where id=#{id}
    </select>
</mapper>

八、Mybatis的注解开发

        1. MyBatis的常用注解

                @Insert:实现新增

                @Update:实现更新

                @Delete:实现删除

                @Select:实现查询

                @Result:实现结果集封装

                @Results:可以与@Result 一起使用,封装多个结果集

                @One:实现一对一结果集封装

                @Many:实现一对多结果集封装

        2. 修改MyBatis的核心配置文件

        我们使用了注解替代的映射文件,所以我们只需要加载使用了注解的Mapper接口即可

<mappers>
    <!--扫描使用注解的类-->
    <mapper class="com.itheima.mapper.UserMapper"></mapper>
</mappers>
<mappers>
    <!--扫描使用注解的类所在的包-->
    <package name="com.mapper"></package>
</mappers>

        3. MyBatis的注解实现复杂映射开发

        实现复杂关系映射之前我们可以在映射文件中通过配置<resultMap>来实现,使用注解开发后,我们可以使用@Results注解,@Result注解,@One注解,@Many注解组合完成复杂关系的配置

注解

说明

@Results

代替的是标签<resultMap>该注解中可以使用单个@Result注解,也可以使用@Result集合。使用格式:@Results({@Result(),@Result()})或@Results(@Result())

@Resut

代替了<id>标签和<result>标签

@Result中属性介绍:

column:数据库的列名

property:需要装配的属性名

one:需要使用的@One 注解(@Result(one=@One)()))

many:需要使用的@Many 注解(@Result(many=@many)()))

@One (一对一)

代替了<assocation> 标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。

@One注解属性介绍:

select: 指定用来多表查询的 sqlmapper

使用格式:@Result(column=" ",property="",one=@One(select=""))

@Many (多对一)

代替了<collection>标签, 是是多表查询的关键,在注解中用来指定子查询返回对象集合。

使用格式:@Result(property="",column="",many=@Many(select=""))

                1. 一对一查询 

public interface OrderMapper {
    @Select("select * from orders")
    @Results({
            @Result(id=true,property = "id",column = "id"),
            @Result(property = "ordertime",column = "ordertime"),
            @Result(property = "total",column = "total"),
            @Result(property = "user",column = "uid",
                    javaType = User.class,
                    one = @One(select = "com.mapper.UserMapper.findById"))
    })
    List<Order> findAll();

}
public interface UserMapper {
    @Select("select * from user where id=#{id}")
    User findById(int id);
    
}

                2. 一对多查询

public interface UserMapper {
    @Select("select * from user")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "username",column = "username"),
            @Result(property = "password",column = "password"),
            @Result(property = "birthday",column = "birthday"),
            @Result(property = "orderList",column = "id",
                    javaType = List.class,
                    many = @Many(select = "com.mapper.OrderMapper.findByUid"))
    })
    List<User> findAllUserAndOrder();
}
public interface OrderMapper {
    @Select("select * from orders where uid=#{uid}")
    List<Order> findByUid(int uid);
}

                3. 多对多查询

public interface UserMapper {
    @Select("select * from user")
    @Results({
        @Result(id = true,property = "id",column = "id"),
        @Result(property = "username",column = "username"),
        @Result(property = "password",column = "password"),
        @Result(property = "birthday",column = "birthday"),
        @Result(property = "roleList",column = "id",
                javaType = List.class,
                many = @Many(select = "com.mapper.RoleMapper.findByUid"))
    })
List<User> findAllUserAndRole();
}
public interface RoleMapper {
    @Select("select * from role r,user_role ur where r.id=ur.role_id and ur.user_id=#{uid}")
    List<Role> findByUid(int uid);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值