Sprigboot6.2 数据访问--springboot整合Mybatis

本文介绍MyBatis在SpringBoot项目中的应用,包括依赖导入、数据源配置、JavaBean定义及数据库操作实现。涵盖注解版与配置文件版两种方式,并详细解析了参数处理、对象映射及驼峰命名配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mybaties 是一个优秀的持久层,支持普通的SQL查询存储过程高级映射消除了几乎所有的JDBC代码和手工设置以及对结果集的检索封装,可以将接口和普通的Java对象映射成数据库中的记录
在Springboot项目中的使用:

  1. 导入依赖,完成基本的数据库连接配置和数据源配置
  2. 创建javabena ,用于数据的封装【bean 中的参数类型和参数的名字要和数据库中的保持一致,不然无法进行封装】
  3. 使用Mybatis

注解版

编写Mapper
使用注解版 mybaties 对数据库进行操作 只需要定义方法

@Mapper     告诉Mybaties 这是一个操作数据库的mapper
public interface DepartmentMapper {
    将查询语句写在注解上,从方法的参数中获取值
    
    通过id 查询一个部门
    @Select("select * from department where id=#{id}")
    public department GetDepartmentById(Integer id);

    //删除
    @Delete("delete from department where id = #{id}")
    public int DeleteDepartmentById(Integer id);

    //插入信息
    @Options(useGeneratedKeys=true ,keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int InsertDepartment(department Dep);

    //更新数据
    @Update("update department set departmentName = #{departmentName} where id =#{id}")
    public int updateById(department dep);

}
★★★★sql 语句中 #{xx} 是从当前的参数列表或者是,传入的对象的属性中获取

Controller 测试:

处理数据访问
@RestController
public class mapMybaties {
   忽略Service层,直接使用 注入
    @Autowired
    DepartmentMapper departmentMapper;
    
    查询
    @GetMapping("/dept/{id}")
    public department GetDepartment(@PathVariable("id") Integer id){
        return departmentMapper.GetDepartmentById(id);
    }

    插入
    @GetMapping("/dept")
    public department InsertDept(department dept){ 
     将参数自动封装为对象(SpringMVC中练习过)
     
     departmentMapper.InsertDepartment(dept);
     mapper 上没有@Options 注解时:返回的dept 是传入参数封装的dept
     mapper 中插入信息的方法上@Options  告诉Mybaties 每次使用都会进行主键封装
        return dept;
    }

Mybaties 中的注解:@Options
@Options(useGeneratedKeys=true ,keyProperty = "id")
应用场景:为对象生成自增的主键值
使用的时候:

  departmentMapper.InsertDepartment(dept);
  调用的Inserdepartment 方法上注解@Options 表示,封装对象的时候会将主键值封装
      return dept;

@Options 注解还能够设置缓存时间,在查询之后,将本次的查询数据缓存,节省下一次查询的时间

在数据访问的过程中,要保证封装数据的类中的属性名和数据库中表的列名保持一致不然就无法将对应的值封装
例如:如果bean 中的属性名:departmentName 数据库中的列名:department_name 如果就驼峰命名来说这两个命名是一样的,但是在项目中这是不一样的。
如果想让他们遵循驼峰命名规则,就要进行Mybaties 的配置,开启驼峰命名:

@org.springframework.context.annotation.Configuration
public class mybatiestConfig {
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {
                //开启驼峰命名
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

总结:
1. Mybaties 的工作一定要有Mapper
2.当项目中Mapper 很多的时候,可以在主程序上添加注解:@Mapper Scan(value = “包名”),指定哪一个包下全是Mapper

配置文件版

1. Mybatis 的全局配置文件 2.每一个Mapper的Sql映射配置文件 【 都是XML文件】
【配置文件的写法:依照github 中的Mybatis 中的官方文档】

1. 编写Mapper
@Mapper 
public interface employeeMapper {
    查询
    public employee getEmployeeById(Integer id);
    插入
    public void InsertEmp(employee emp);
}
2.编写配置文件  【全局配置,sql 映射】
【sql 映射文件】
<?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="mybties.mapper.employeeMapper">
    <!--namespace 与接口绑定 将接口中的方法配置到文件中 Sql 映射-->
    
<!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复
使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
resultType="me.gacl.domain.User"就表示将查询结果封装成一个User类的对象返回
User类就是users表所对应的实体类
--> 
    <!--查询-->
    <select id="getEmployeeById" resultType="mybties.bean.employee">  
                                            返回的类型要是类的权限定名
        SELECT * FROM employee WHERE id=#{id}
    </select>
    
    <!--插入-->
    <insert id="InsertEmp" >
         INSERT INTO employee(id,lastName,email,gender,d_id) VALUES (#{id},#{lastName},#{email},#{gender},#{d_id})
    </insert>
</mapper>

#{xxx} 还是从方法的参数列表中获取

【全局配置文件】
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

  <!--配置启动驼峰命名法   全局的配置可以在配置文件中配置-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

将mybatis 的配置在主配置文件中进行声名
mybatis:
    config-location: classpath:mybatis/mybatis-config.xml
    mapper-locations: classpath:mybatis/Mapper/*.xml
    
最后编写Contoller 测试

注意sql 语句中的参数问题:
mybatis自动识别入参对象, 传入单个map或单个对象,无需写@Param注解

分析:
 通过id 查询一个部门
@Select("select * from department where id=#{id}")
public department GetDepartmentById(Integer id);

如果参数的参数有多个就要进行绑定

@Select("select * from department where id=#{id}")
public department GetDepartmentById(@Param("id")  Integer a); 
就将sql 语句中的参数和方法上传入的参数进行了绑定

无论是注解版还是配置文件版都要遵循这样的参数规则,否则是无法完成查询的

mybatis可以传入的参数类型

  1. 基本数据类型
    可以通过#{参数名}直接获取。每次只能传入一个值
  2. 自定义类
    可以传入一个对象,通过#{对象中的property或field}获取对象中存放的值,如果自定义对象user内还存在自定义对象address的话可以通过address.id获取address的属性值。
    < select id="selectTeacher" parameterType="teacher" resultType="com.myapp.domain.Teacher"> select * from Teacher where c_id=#{id};
    < select id="selectTeacher" parameterType="teacher" resultType="com.myapp.domain.Teacher"> select * from Teacher where a_id=#{address.id};
  3. Map集合
    传入一个Map集合,通过#{key}获取存在Map中的value值
    < select id=“selectTeacher” parameterType=“java.util.Map” resultType=“com.myapp.domain.Teacher”> select * from Teacher where c_id=#{id}
  4. 数组|集合
    传入数据的话,需要使用下标当做key值,获取value
    < select id=“selectTeacher” resultType=“com.myapp.domain.Teacher”> select * from Teacher where c_id=#{0} and address.id = #{1}
  5. 注解【使用@Param】
    可以在接口内传入多个参数,这时mybatis会把多个参数当成一个数组使用,使用下标获取值。可以使用注解,给每个变量设置一个key,在取值的时候通过这个key获取。
    public List< User> selectUserByPage(@Param(value=“startIndex”)int startIndex,@Param(“rows”)int rows);
    这样传入时就相当于是传入了一个Map集合

parameterType可以使用的值为基本数据类型,自定义类型,Map集合,数组,list
在使用数组和list时,如果要使用foreach标签,则collection的值必须为array或者list,不管传入的参数名为什么。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值