MyBatis Mapper四步走

1. 定义承载结果的Java类充当领域对象(不使用MyBatis的内置map)。

2.开发Mapper组件,也就是接口+XML(或注解)

3.获取SqlSession,在获取Mapper组件对象。

4.调用Mapper组件的方法操作数据库。

---------------------------------------------------------------------------------------------------------------------------------

实操一下,数据库名称mydept,数据表dept:

1.创建可以充当领域对象的JAVA类:entity.Dept

 

省略了无参构造器,全参构造器,getter/setter和toString。

2. 构建Mapper组件

定义dao.MyDeptMapper接口 

public interface MyDeptMapper {
   int addDept(Dept dept);
   int updateDept(Dept dept);
   int removeDept(int id);
   Dept get(int id);
   List<Dept> getAll();
}

定义XML文档,按照映射规则接口与XML文档要同名同包同id。

所以XML文档要建立在resources下的dao目录下,与java源文件目录下的dao.MyDeptMapper接口对应上。

 然后要在mybatis-config.xml中描述清楚MyDeptMapper.xml的位置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development" ...>
        
    <mappers>
        <mapper resource="dao/MyDeptMapper.xml"/>
    </mappers>

</configuration>

只需关注mybatis-config.xml中<mappers>的部分,要以目录的形式(但是不要写resources)呈现出MyDeptMapper.xml的位置。(注意,这并不是唯一的写法,也可以用<mapper class=xxx.xxx.接口>的方式建立映射关系。)

随后可以开始编辑MyDeptMapper.xml的具体内容了:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.MyDeptMapper">
    <insert id="addDept">
        insert into dept values(null,#{name},#{loc})
    </insert>
    <update id="updateDept">
        update dept set name=#{name}, loc=#{loc} where id=#{id}
    </update>
    <delete id="removeDept">
        delete from dept where id = #{id}
    </delete>
    <select id="get" resultType="entity.Dept">
        select * from dept where id=#{id}
    </select>
    <select id="getAll" resultType="entity.Dept">
        select * from dept
    </select>

</mapper>

这里只需注意两个点:

  1. namespace对应接口的位置。
  2. select标签的returnType对应前面写的“领域”类

3. 获取SqlSession

String configXML = "mybatis-config.xml";
InputStream stream = Resources.getResourceAsStream(configXML);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
SqlSession sqlSession = sqlSessionFactory.openSession();

4.通过session调用Mapper组件操作数据库:

//省略了导包的相关代码 import dao.MyDeptMapper;
MyDeptMapper mapper = session.getMapper(MyDeptMapper.class);
List<Dept> depts = mapper.getAll();
System.out.printf("%d rows.",depts.size());

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值