Mybatis(注解实现增删改查,XML配置文件,动态SQL)

目录

 准备

删除,插入,修改,查询

日志输出

 预编译SQL

 新增(主键返回)

 数据封装

 XML映射文件

 MybatisX

动态SQL

 

案例,动态更新员工信息

 

 


 准备

 lombok:简化实体类定义

    <dependencies>
//mybatis的起步依赖
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
//mysql驱动包
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
//lombok依赖
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
//springboot进行单元测试依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
#连按数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=123456 

#配置mybatis的日志, 指定输出到控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#开启mybatis的驼峰命名自动映射开关 a_column ------> aCloumn
mybatis.configuration.map-underscore-to-camel-case=true
 

 @Mapper:程序在运行会自动创建该接口的代理对象,并且将这个代理对象放IOC容器中

注意:

1.如果mapper接口方法形参只有一个普通类型的参数,#{…} 里面的属性名可以随便写,如:#{id}、#{value}。

2.在测试调用empmapper中的insert方法,里面传递一个员工对象,为员工对象当中的各个属性进行赋值操作,执行语句时,自动获取emp对象的各个属性值

3.查询有返回值

4. 查询时,字符串拼接函数concat

删除,插入,修改,查询

Empmapper接口中:

@Mapper
public interface EmpMapper {

    //根据主键ID删除数据 
    @Delete("delete from emp where id = #{id}")
   public void  delete(Integer id);

    public int delete(Integer id);
    


    //新增员工  (多个参数封装到一个对象当中,再调用insert方法,传递一个对象
    @Options(useGeneratedKeys = true, keyProperty = "id")   //获取返回的主键
   

@Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time)" +
            " values (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")
    public void insert(Emp emp);  //实体对象进行封装


    //更新员工
    @Update("update emp set username = #{username}, name = #{name}, gender = #{gender}, image = #{image}," +
            " job = #{job}, entrydate = #{entrydate}, dept_id = #{deptId},update_time = #{updateTime} where id = #{id}")
    public void update(Emp emp);

   
    //数据封装方案三: 开启mybatis的驼峰命名自动映射开关 --- a_cloumn ------> aColumn (在配置文件中)


    //根据ID查询员工
   @Select("select * from emp where id = #{id}")
    public Emp getById(Integer id);
  

    //条件查询员工
    //方式二
   @Select("select * from emp where name like concat(' % ',#{name},' % ') and gender = #{gender} and " +
           "entrydate between #{begin} and #{end} order by update_time desc ")
 public List<Emp> list(String name, Short gender, LocalDate begin , LocalDate end); //接口方法

单元测试中:

@Autowired
    private EmpMapper empMapper;

    //根据ID删除
    @Test
    public void testDelete(){
        //int delete = empMapper.delete(16);
        //System.out.println(delete);
        empMapper.delete(16);
    }

    //新增员工
    @Test
    public void testInsert(){
        //构造员工对象
        Emp emp = new Emp();
        emp.setUsername("Tom3");
        emp.setName("汤姆3");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2000,1,1));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        //执行新增员工信息操作
        empMapper.insert(emp);
        System.out.println(emp.getId());  //获取返回主键值
    }

    //更新员工
    @Test
    public void testUpdate(){
        //构造员工对象
        Emp emp = new Emp();
        emp.setId(18);
        emp.setUsername("Tom1");
        emp.setName("汤姆1");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2000,1,1));
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        //执行更新员工操作
        empMapper.update(emp);
    }


    //根据ID查询员工
    @Test
    public void testGetById(){
        Emp emp = empMapper.getById(20);
        System.out.println(emp);
    }


    //根据条件查询员工
    @Test
    public void testList(){
        List<Emp> empList = empMapper.list("张", (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
        System.out.println(empList);
    }
}

日志输出

可以在application.properties中,打开mybatis的日志,并指定输出到控制台。

 预编译SQL

 优势:性能更高 更安全(防止SQL注入)

SQL注入是通过操作输入的数据来修改事先定义好的SQL语句,以达到执行代码对服务器进行攻击的方法。

 新增(主键返回)

描述:在数据添加成功后,需要获取插入数据库数据的主键。如:添加套餐数据时,还需要维护套餐菜品关系表数据。

 数据封装

实体类属性名 和 数据库表查询返回的字段名一致,mybatis会自动封装。

如果实体类属性名 和 数据库表查询返回的字段名不一致,不能自动封装。

三种方法(选第三种):

 XML映射文件

  • XML映射文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包下(同包同名)。
  • XML映射文件的namespace属性为Mapper接口全限定名一致。
  • XML映射文件中sql语句的id与Mapper 接口中的方法名一致,并保持返回类型一致。

 建包

 

全限定名:

 

 

 MybatisX

MybatisX 是一款基于 IDEA 的快速开发Mybatis的插件,为效率而生。

 

使用Mybatis的注解,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句。

动态SQL

 随着用户的输入或外部条件的变化而变化的SQL语句,我们称为动态SQL。

<if>

用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL。

形式:

<if test="name != null">

name like concat('%',#{name},'%')

</if>

 <where>

(if里面有一个条件成立,就会生成where关键字)

where 元素只会在子元素有内容的情况下才插入where子句,

而且会自动去除子句的开头的AND 或OR。

XML中 : 

EmpMapper.java中:

//动态条件查询
    public List<Emp> list(String name, Short gender, LocalDate begin , LocalDate end)

 SpringbootMybatisCrudApplicationTests中:

    //根据条件查询员工
    @Test
    public void testList(){
        //List<Emp> empList = empMapper.list("张", null, null, null);     //只查询name
        //List<Emp> empList = empMapper.list("张", (short)1, null, null);  
        //List<Emp> empList = empMapper.list(null, (short)1, null, null);
        List<Emp> empList = empMapper.list(null, null, null, null);  //全部员工信息
        System.out.println(empList);
    } 

案例,动态更新员工信息

需求:如果更新时传递有值,则更新;如果更新时没有传递值,则不更新为null。

 EmpMapper.java中:

    //动态更新员工
    public void update2(Emp emp); 

<set>

动态地在行首插入 SET 关键字,并会掉额外的逗号。(用在update语句中)

 XML中:(alt+回车)

    <!-- 动态更新员工-->
    <update id="update2">
        update emp
        <set>
            <if test="username != null">username = #{username},</if>
            <if test="name != null">name = #{name},</if>
            <if test="gender != null">gender = #{gender},</if>
            <if test="image != null">image = #{image},</if>
            <if test="job != null">job = #{job},</if>
            <if test="entrydate != null">entrydate = #{entrydate},</if>
            <if test="deptId != null">dept_id = #{deptId},</if>
            <if test="updateTime != null">update_time = #{updateTime}</if>
        </set>
        where id = #{id}
    </update>

 SpringbootMybatisCrudApplicationTests中: 

    //动态更新员工 - 更新ID为18的员工 username 更新为 Tom111, name更新为 汤姆111, gender更新为2
    @Test
    public void testUpdate2(){
        //构造员工对象
        Emp emp = new Emp();
        emp.setId(19); 
        emp.setUsername("Tom222333");
//        emp.setName("汤姆222");
//        emp.setGender((short)1);
//        emp.setUpdateTime(LocalDateTime.now());

        //执行更新员工操作
        empMapper.update2(emp);
    }
 

 <for each>

循环遍历,可以用于批量删除

SQL语句

 delete from emp where id in (1,2,3);

 EmpMapper.java中:

//批量删除员工 18,19,20
    public void deleteByIds(List<Integer> ids);

EmpMapper.xml中:

 <!--批量删除员工 (18,19,20)-->
    <!--
        collection: 遍历的集合
        item: 遍历出来的元素 变量名
        separator: 分隔符
        open: 遍历开始前拼接的SQL片段
        close: 遍历结束后拼接的SQL片段
    -->

    <delete id="deleteByIds"> 
        delete  from emp where id in
        <foreach collection="ids" item="id" separator="," open="("  close=")">
            #{id}
        </foreach>
    </delete>

 SpringbootMybatisCrudApplicationTests中:   

 //批量删除员工 - 13,14,15
    @Test
    public void testDeleteByIds(){
        List<Integer> ids = Arrays.asList(13, 14, 15);
        empMapper.deleteByIds(ids);
    }

 <sql><include>

 <sql>:定义可重用的 SQL 片段。共同sql片段抽取

 <include>:通过属性refid,引入sql片段

XML中:

<sql id="commonSelect">  

select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp

</sql>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值