springboot整合mybatis

SpringBoot整合mybatis

bean类

//department
package com.example.springbootjdbc.bean;

public class Department {
    Integer id;
    String departmentName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
}
//employee
package com.example.springbootjdbc.bean;

public class Employee {
    Integer id;
    String lastName;
    String email;
    Integer gender;
    Integer dId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Integer getdId() {
        return dId;
    }

    public void setdId(Integer dId) {
        this.dId = dId;
    }
}

引入依赖

   <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

注解方式整合mybatis

  • 创建mapper文件

针对mapper接口需要在具体接口上写上@mapper注解,或者在启动类上面标记上@MapperScan(value = “classpath”),classpath可以指具体接口,也可以设置为所有接口的文件夹路径,可以将所有的mapper接口扫描进去。

例如:@MapperScan(value = "com.example.springbootjdbc.mapper")

//启动类

@MapperScan(value = "com.example.springbootjdbc.mapper")
@SpringBootApplication
public class SpringbootjdbcApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootjdbcApplication.class, args);
    }

}
//mapper接口文件
package com.example.springbootjdbc.mapper;

import com.example.springbootjdbc.bean.Department;
import com.sun.javafx.tk.TKPulseListener;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

//@Mapper//指定这是一个操作数据库的mapper
@Repository
public interface DepartmentMapper {
  
    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);
    @Delete("delete from department where id = #{id}")
    public  int deleteById(Integer id);
    @Options(useGeneratedKeys = true,keyProperty = "id")//插入之后重新将自增主键封装到对象中
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);
}
  • 进行增删查改操作分别使用以下注解:
    • @select(“sql”)
    • @deelete(“sql”)
    • @insert(“sql”)
    • @update(“sql”)
  • 其他注解
    • @options()
      • useGeneratedKeys = true:是否启动主键自增
      • keyProperty = “id”:设置主键
    • @repository:在引用mapper接口时防止报错(报错不是致命错误,不影响程序正常运行)

修改mybatis默认配置:

package com.example.springbootjdbc.config;

import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisConfig {
    //自定义mybatis的配置规则
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                //开启驼峰命名
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

配置文件方式整合mybatis

mybatis官方文档:https://mybatis.org/mybatis-3/zh/sqlmap-xml.html#insert_update_and_delete

  • 全局配置文件
    • 直接在官网上复制格式,将configuration标签内的值删除
      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-27tVYm6z-1607479285356)(/Users/gaoqi/Documents/Note/java/java/整合mybatis/image-20201209093604637.png)]

    • 将所需要配置在configuration标签内设置

各属性:https://mybatis.org/mybatis-3/zh/configuration.html#settings
目录结构:resources/mybatis/mybatisConfig.xml

<?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>
  <!--是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。-->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

</configuration>

编写mapper接口

package com.example.springbootjdbc.mapper;

import com.example.springbootjdbc.bean.Employee;
import com.example.springbootjdbc.controller.EmployeeController;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

//使用mapper或者mappersacn(value="classpath")来指定操作数据库的接口位置

@Repository
public interface EmployeeMapper {
// 通过id获取员工信息
    public Employee getEmpById(Integer id);
// 插入一条员工数据
    public int insertEmp(Employee employee);
}

写入映射文件

目录结构:resources/mybatis/mapper/employeeMapper.xml

<?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="com.example.springbootjdbc.mapper.EmployeeMapper">
<!--        id为方法名,resultType为返回值的类型,使用全类名-->
    <select id="getEmpById" resultType="com.example.springbootjdbc.bean.Employee">

        select * from employee where id = #{id}
    </select>
	<!--    emtployee (lastName,email,gender,d_id)对应到数据库表中的字段名-->
    <!--    values的值为插入对象的值类型,参数名要要和对象中属性对应,通过#{}来取值-->
    <insert id="insertEmp"  keyProperty="id" useGeneratedKeys="true">
        insert into emtployee (lastName,email,gender,d_id)
        values (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>
  • 相关参数
    • namespace:命名空间,表示对应的mapper接口路径
  • 增删查改
    • select标签:
      • 进行查询操作,通过#{}来获取参数值
      • 标签内id属性表示mapper内对应的增删改查方法名
      • resultType为返回值类型,如果为对象则写入类名(当类名唯一)或者类的路径
    • insert标签:
      • keyProperty设置主键
      • useGeneratedKeys设置是否自增

1、报错:Exception encountered during context initialization
cancelling refresh attempt: org.springframework.beans.factory.
UnsatisfiedDependencyException: Error creating bean with name ‘departmentController’:
Unsatisfied dependency expressed through field ‘departmentMapper’;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name ‘departmentMapper’ defined in file
原因在insert标签中写入了注释

在项目配置文件中申明mybatis配置文件等信息

mybatis:
  #全局配置文件
  config-location: classpath:mybatis/mybatisConfig.xml
  #mapper配置文件
  mapper-locations: classpath:mybatis/mapper/*.xml

编写controller文件

package com.example.springbootjdbc.controller;

import com.example.springbootjdbc.bean.Employee;
import com.example.springbootjdbc.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class EmployeeController {

    //employee报错不解决扔可以运行,解决方法在mapper接口中加上registry注解
    @Autowired
    EmployeeMapper employeeMapper;

    @ResponseBody
    @GetMapping("/emp/{id}")
    //通过url获取参数值,使用pathVariable标签
    public Employee getEmp(@PathVariable("id") Integer id){
        return employeeMapper.getEmpById(id);
    }
    @ResponseBody
    @GetMapping("/emp")
    //通过url传入对应的参数,springboot直接将参数封装为employee对象
    public Employee insertEmp(Employee employee){
        employeeMapper.insertEmp(employee);
        return employee;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值