简单学习MyBatis

mybatis中,封装了一个sqlsession 对象(里面封装有connection对象),由此对象来对数据库进行CRUD操作。

1、Mapper.xml:

目的:编写SQL语句

namespace:命名空间,Mapper XML文件中的语句的唯一标识,避免在不同的Mapper XML文件中存在相同的语句

resultType:自动映射(全类名),只有在表的列名与POJO类的属性完全一致时使用。

<mapper namespace="xxxMapper">
    <select id="xxx" resultType="com.xxx">
        select * from xxx
    </select>
</mapper>

如果属性和表的列名不一致,可以使用列名映射resultMap标签(自动转为别名)

<resultMap id="baseResultMap" type="com.xxx">
    <!--使用映射,把对应的列名映射为对应的属性 -->
    <id property="a" column="A" />
    <result property="b" column="B"/>
</resultMap>
<!--引用上面定义的resultMap-->
<select id="selectAll" resultMap="baseResultMap">
    select * from xxx
</select>

resultType属性需要全类名,我们可以使用typeAliases标签来简化输入。
                 方法:在mybatis-config.xml文件中进行设置,实现用类名取代全类名。

<!--指定一个bean包 -->
<typeAliases>
      <package name="com.wan.bean"/>
</typeAliases>

2、mybatis-config.xml:

目的:配置数据源 和 映射Mapping

注册mapper的三种方法

(1)文件路径注册

<mappers>
    <mapper resource="com/xxx/xxxMapper.xml"/>
</mappers>

(2)包名扫描注册,前提:保证xxxMapper.java和xxxMapper.xml两者名字一模一样,而且是要在同一包里!

<mappers>
    <package name="com.xxx" />
</mappers>

(3)类名注册

<mappers>
    <mapper class="com.xxxMapper" />
</mappers>

 3、mybatis约定:(很重要)

(1)接口方法名与mapper中的id相同
(2)接口方法参数与parameterType类型相同
(3)接口方法的返回值类型与resultType类型相同
遵守约定:Mybatis就会将接口类中的方法和mapper中的sql语句一一对应起来,而不需要再次新建一个Dao,在Dao类里面编写方法。

 

方式:动态代理

   (1)接口类:

public interface EmployeeMapper {
    List<Employee> selectAll();
}

   (2)Mapper.xml:

<mapper namespace="com.wan.mapping.EmployeeMapper">
    <!--特例:返回值为list,resultType=bean类-->
    <select id="selectAll" resultType="Employee" >
        select * from employee
    </select>
</mapper>

  (3)mybatis-config.xml:

<configuration>
    <!--省略数据源配置 -->...
    <!-- 注册SQL映射文件,在这些文件中写SQL语句 -->
    <mappers>
    <!--指定整个包中的全部Mapper -->
        <package name="com.wan.mapper"/>
    </mappers>
</configuration>

 (4)service层调用:

Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
//build方法可以接受几种不同的参数,如Reader/InputSteam等
SqlSession sqlSession = factory.openSession();
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
//注入接口动态代理生成映射器(代理类)
List<Employee> employees = mapper.selectAll();

 

dependency:mybatis

更详细教程,点击这里

原文地址:https://www.cnblogs.com/mo-jian-ming/p/13276730.html