[mybatis]Mapper XML Files_CUD

Posted 唐火

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[mybatis]Mapper XML Files_CUD相关的知识,希望对你有一定的参考价值。

The true power of MyBatis is in the Mapped Statements. This is where the magic happens.

CUD

  • mybatis运行CUD直接定义以下类型返回值
    • Integer,Long,Boolean
  • 我们需要手动提交数据
    • sqlSessionFactory.openSession();—>手动提交
    • sqlSessionFactory.openSession(true);—>自动提交

接口:

package com.atguigu.mybatis.dao;

import com.atguigu.mybatis.bean.Employee;

public interface EmployeeMapper 


    public Employee getEmpById(Integer id);

    public Long addEmp(Employee employee);

    public boolean updateEmp(Employee employee);

    public void deleteEmpById(Integer id);





映射文件:

<?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="com.atguigu.mybatis.dao.EmployeeMapper">



<select id="getEmpById" resultType="employee">

    select id,last_name,email,gender from tb1_employee where id = #id

</select>

    <!--parameterType:可以省略-->
    <insert id="addEmp" parameterType="com.atguigu.mybatis.bean.Employee" useGeneratedKeys="true" keyProperty="id" >

        insert into tb1_employee(last_name,email,gender)
        values(#lastName,#email,#gender)
    </insert>


    <!--public void updateEmp(Employee employee)-->

    <update id="updateEmp">
        update tb1_employee
            set last_name = #lastName,email = #gender
            where id = #id

    </update>



    <!--public void deleteEmpById(Integer id);-->
    <delete id = "deleteEmpById">

    delete from tb1_employee where id = #id
</delete>


</mapper>

在这里就测试一个addEmp函数:

  @Test
    public void test02() throws IOException 

        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();

        SqlSession sqlSession = sqlSessionFactory.openSession();

        try
        
            EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);

            Employee employee = new Employee(null, "jack", "jack@qq.com", "1");


            mapper.addEmp(employee);

            //手动提交数据
            sqlSession.commit();


        finally 

            sqlSession.close();

        


    

以上是关于[mybatis]Mapper XML Files_CUD的主要内容,如果未能解决你的问题,请参考以下文章

mybatis自动生成dao, model, mapper xml文件

idea怎么从mapper进xml

mybatis 关联对象mapper.xml的写法

mapper.xml的使用

干掉mapper.xml!MyBatis新特性动态SQL真香!

MyBatis 的mapper.xml配置的问题