[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);



}

映射文件:


        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>

    
    <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>


    

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

    update>



    
    <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", "[email protected]", "1");


            mapper.addEmp(employee);

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


        }finally {

            sqlSession.close();

        }


    }

你可能感兴趣的:(mybatis,xml,java,java-ee)