一.查询
根据id来查询字段
package com.gjw;import com.gjw.mapper.EmpMapper;
import com.gjw.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;
import java.util.List;@SpringBootTest
class SpringbootMybatisCrudApplicationTests {@Autowiredprivate EmpMapper empMapper;@Testvoid contextLoads() {}@Testpublic void testSelectById() {Emp e = empMapper.selectById(1);System.out.println(e);}
}
package com.gjw.mapper;import com.gjw.pojo.Emp;
import org.apache.ibatis.annotations.*;import java.time.LocalDate;
import java.util.List;@Mapper
public interface EmpMapper {@Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id = #{id}")public Emp selectById(Integer id);
}
这样查询出来的数据会有一定的问题,如下图所示:
这三个字段的数据并没有封装到mybatis当中去,因为字段名和实体类的属性名并不一致。在数据库字段中为dept_id,而在实体类属性名中却是驼峰命名的方式。
二.数据封装问题
三.如何解决
解决方法1:起别名,让数据库字段别名和实体类属性名保持一致
package com.gjw.mapper;import com.gjw.pojo.Emp;
import org.apache.ibatis.annotations.*;import java.time.LocalDate;
import java.util.List;@Mapper
public interface EmpMapper {// 解决方法1:起别名,让数据库字段别名和实体类属性名保持一致@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 select(Integer id);
}
解决方法2:使用@Results,@Result注解手动映射封装
package com.gjw.mapper;import com.gjw.pojo.Emp;
import org.apache.ibatis.annotations.*;import java.time.LocalDate;
import java.util.List;@Mapper
public interface EmpMapper {// 解决方法2:使用@Results,@Result注解手动映射封装@Results({@Result(column = "dept_id",property = "deptId"),@Result(column = "create_time",property = "createTime"),@Result(column = "update_time",property = "updateTime")})@Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id = #{id}")public Emp select(Integer id);
}
解决方法3:开启mybatis的驼峰命名自动映射开关 --- a_column -----> aColumn(推荐)
我们首先要在配置文件application.properties中进行配置,将开关开启
spring.application.name=springboot-mybatis-crud
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.password=
spring.datasource.username=root# 配置在控制台输出日志信息
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl# 配置mybatis的驼峰命名自动映射开关 --- a_column -----> aColumn(camel:骆驼)
mybatis.configuration.map-underscore-to-camel-case=true
package com.gjw.mapper;import com.gjw.pojo.Emp;
import org.apache.ibatis.annotations.*;import java.time.LocalDate;
import java.util.List;@Mapper
public interface EmpMapper {// 解决方法3:开启mybatis的驼峰命名自动映射开关 --- a_column -----> aColumn@Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id = #{id}")public Emp selectById(Integer id);
}
这样就能自动解决数据封装问题了。