Mybatis-基础操作-查询

一.根据ID查询:

1.SQL语句:

2.Mybatis演示:

a.EmpMapper接口里:
package com.itheima.mapper;
​
import com.itheima.pojo.Emp;
import org.apache.ibatis.annotations.*;
​
@Mapper
public interface EmpMapper {
​
    //根据ID删除数据-->需要注解@Delete
    /* 删除的id不确定,因此需要定义为动态的,在调用接口里的方法时要用到id,
       所以要传递一个参数表示id。由于是动态的,还需要
     Mybatis里提供的参数占位符即#{参数名字}
     */
    @Delete("delete from emp where id = #{id}")
    public int delete(Integer id); //有返回值时代表一共操作了几条记录
​
​
​
    //新增员工
    @Options(useGeneratedKeys = true,keyProperty = "id")
     //useGeneratedKeys = true代表需要拿到生成的主键值,keyProperty = "id"代表获取的主键最终会封装到Emp对象的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);//形参是pojo里的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);
​
​
    //根据ID查询员工
    /*本例中根据id查询到的员工只有一个,因此用员工对象即可,无需集合*/
    @Select("select * from emp where id=#{id}")
    public Emp getById(Integer id);
​
}
b.测试类:
package com.itheima;
​
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
​
import java.time.LocalDate;
import java.time.LocalDateTime;
​
@SpringBootTest
class SpringbootMybatisCrudApplicationTests {
​
    //注入接口对象
    @Autowired
    private EmpMapper empMapper;
​
    @Test
    public void testDelete(){
        int delete = empMapper.delete(16);
        System.out.println(delete);//运行结果为0
        /* 因为刚才已经把id为17的员工删除了,此时就无法删除了,
           故操作了0条数据
         */
    }
​
​
    @Test //@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());//运行结果为21,代表id为21
    }
​
​
    @Test
    public void testUpdate(){
        //构造员工对象
        Emp emp=new Emp();
        emp.setId(18);//把id为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());//要设置为当前时间,每一次更新都需要更改updateTime
        emp.setDeptId(1);
​
        //执行更新员工操作
        empMapper.update(emp);
    }
    
    
    //根据ID查询员工
    @Test
    public void testGetById(){
        Emp emp=empMapper.getById(20);
        System.out.println(emp);
    }
​
}
c.运行结果:

-->但deptId,createTime,updateTime均为null-->这有关Mybatis的数据封装,解释如下:

二.解决数据不能自动封装的方案:(解决数据库字段名与实体类属性名不一致导致输出为null的问题的方案)

方案1: 给字段起别名,让别名与实体类属性名一致:

a.EmpMapper接口里:
package com.itheima.mapper;
​
import com.itheima.pojo.Emp;
import org.apache.ibatis.annotations.*;
​
@Mapper
public interface EmpMapper {
​
    //根据ID删除数据-->需要注解@Delete
    /* 删除的id不确定,因此需要定义为动态的,在调用接口里的方法时要用到id,
       所以要传递一个参数表示id。由于是动态的,还需要
     Mybatis里提供的参数占位符即#{参数名字}
     */
    @Delete("delete from emp where id = #{id}")
    public int delete(Integer id); //有返回值时代表一共操作了几条记录
​
​
​
    //新增员工
    @Options(useGeneratedKeys = true,keyProperty = "id")
     //useGeneratedKeys = true代表需要拿到生成的主键值,keyProperty = "id"代表获取的主键最终会封装到Emp对象的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);//形参是pojo里的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);
​
​
    /*//根据ID查询员工
    *//*本例中根据id查询到的员工只有一个,因此用员工对象即可,无需集合*//*
    @Select("select * from emp where id=#{id}")
    public Emp getById(Integer id);*/
​
​
    //由于要给数据库的字段起别名,此时不能用select * from,其中的*要换成所有字段
    @Select("select id, username, password, name, gender, image, job, entrydate, " +
            "dept_id deptId, create_time createTime, update_time updateTime from emp where id=#{id}")
    public Emp getById(Integer id);
​
}
​
b.测试类:
package com.itheima;
​
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
​
import java.time.LocalDate;
import java.time.LocalDateTime;
​
@SpringBootTest
class SpringbootMybatisCrudApplicationTests {
​
    //注入接口对象
    @Autowired
    private EmpMapper empMapper;
​
    @Test
    public void testDelete(){
        int delete = empMapper.delete(16);
        System.out.println(delete);//运行结果为0
        /* 因为刚才已经把id为17的员工删除了,此时就无法删除了,
           故操作了0条数据
         */
    }
​
​
    @Test //@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());//运行结果为21,代表id为21
    }
​
​
    @Test
    public void testUpdate(){
        //构造员工对象
        Emp emp=new Emp();
        emp.setId(18);//把id为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());//要设置为当前时间,每一次更新都需要更改updateTime
        emp.setDeptId(1);
​
        //执行更新员工操作
        empMapper.update(emp);
    }
​
​
    //根据ID查询员工
    @Test
    public void testGetById(){
        Emp emp=empMapper.getById(20);
        System.out.println(emp);
    }
​
}
c.运行结果:


方案2:通过注解@Results,@Result手动映射封装:

a.EmpMapper接口里:
package com.itheima.mapper;
​
import com.itheima.pojo.Emp;
import org.apache.ibatis.annotations.*;
​
@Mapper
public interface EmpMapper {
​
    //根据ID删除数据-->需要注解@Delete
    /* 删除的id不确定,因此需要定义为动态的,在调用接口里的方法时要用到id,
       所以要传递一个参数表示id。由于是动态的,还需要
     Mybatis里提供的参数占位符即#{参数名字}
     */
    @Delete("delete from emp where id = #{id}")
    public int delete(Integer id); //有返回值时代表一共操作了几条记录
​
​
​
    //新增员工
    @Options(useGeneratedKeys = true,keyProperty = "id")
     //useGeneratedKeys = true代表需要拿到生成的主键值,keyProperty = "id"代表获取的主键最终会封装到Emp对象的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);//形参是pojo里的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);
​
​
    /*//根据ID查询员工
    *//*本例中根据id查询到的员工只有一个,因此用员工对象即可,无需集合*//*
    @Select("select * from emp where id=#{id}")
    public Emp getById(Integer id);*/
​
​
    @Results({ //只对属性名和字段名不一致的进行手动封装即可
            @Result(column = "dept_id",property = "deptId"),  
            //column代表表中的字段名,property代表类中的属性名-->代表手动映射哪个字段,把字段封装到哪个属性中
            /* 一个@Result注解用来映射一个字段和属性 */
            @Result(column = "create_time",property = "createTime"),
            @Result(column = "update_time",property = "updateTime")
    })
     /* @Results用来封装结果,当中有一个属性value-->是数组,
        当中需要@Result对象
      */
    @Select("select * from emp where id=#{id}")
    public Emp getById(Integer id);
​
}
​
b.测试类:
package com.itheima;
​
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
​
​
@SpringBootTest
class SpringbootMybatisCrudApplicationTests {
​
    //注入接口对象
    @Autowired
    private EmpMapper empMapper;
​
    @Test
    public void testDelete(){
        int delete = empMapper.delete(16);
        System.out.println(delete);//运行结果为0
        /* 因为刚才已经把id为17的员工删除了,此时就无法删除了,
           故操作了0条数据
         */
    }
​
    //根据ID查询员工
    @Test
    public void testGetById(){
        Emp emp=empMapper.getById(20);
        System.out.println(emp);
    }
​
}
c.运行结果:


方案3:开启Mybatis的驼峰命名自动映射开关,如create_time自动更改为createTime

(方案3前提条件:数据库的字段名是下划线分隔,类中的属性名是驼峰命名)
a.开启这个开关的代码:
# 开启mybatis的驼峰命名自动映射开关
mybatis.configuration.map-underscore-to-camel-case=true
图片:

b.EmpMapper接口里:
package com.itheima.mapper;
​
import com.itheima.pojo.Emp;
import org.apache.ibatis.annotations.*;
​
@Mapper
public interface EmpMapper {
​
    //根据ID删除数据-->需要注解@Delete
    /* 删除的id不确定,因此需要定义为动态的,在调用接口里的方法时要用到id,
       所以要传递一个参数表示id。由于是动态的,还需要
     Mybatis里提供的参数占位符即#{参数名字}
     */
    @Delete("delete from emp where id = #{id}")
    public int delete(Integer id); //有返回值时代表一共操作了几条记录
​
​
​
    //新增员工
    @Options(useGeneratedKeys = true,keyProperty = "id")
     //useGeneratedKeys = true代表需要拿到生成的主键值,keyProperty = "id"代表获取的主键最终会封装到Emp对象的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);//形参是pojo里的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);
​
​
    /*//根据ID查询员工
    *//*本例中根据id查询到的员工只有一个,因此用员工对象即可,无需集合*//*
    @Select("select * from emp where id=#{id}")
    public Emp getById(Integer id);*/
​
​
    
    @Select("select * from emp where id=#{id}")
    public Emp getById(Integer id);
​
}
c.测试类:
package com.itheima;

import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

	//注入接口对象
	@Autowired
	private EmpMapper empMapper;
	
	//根据ID查询员工
	@Test
	public void testGetById(){
		Emp emp=empMapper.getById(20);
		System.out.println(emp);
	}

}
d.运行结果:


三.数据封装总结:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值