文章目录
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接口时防止报错(报错不是致命错误,不影响程序正常运行)
- @options()
修改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标签内的值删除
-
将所需要配置在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设置是否自增
- select标签:
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;
}
}