spring-boot-route(八)整合mybatis操做數據庫

MyBatis 是一款優秀的持久層框架,它支持定製化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎全部的 JDBC 代碼和手動設置參數以及獲取結果集。MyBatis 能夠使用簡單的 XML 或註解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java對象)映射成數據庫中的記錄。java

經過註解完成數據操做

第一步:引入mysql依賴和mybatis依賴mysql

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>LATEST</version>
</dependency>

第二步:新建學生表及對應的實體類git

CREATE TABLE `student` (
   `student_id` int(30) NOT NULL AUTO_INCREMENT,
   `age` int(1) DEFAULT NULL COMMENT '年齡',
   `name` varchar(45) DEFAULT NULL COMMENT '姓名',
   `sex` int(1) DEFAULT NULL COMMENT '性別:1:男,2:女,0:未知',
   `create_time` datetime DEFAULT NULL COMMENT '建立時間',
   `status` int(1) DEFAULT NULL COMMENT '狀態:1:正常,-1:刪除',
   PRIMARY KEY (`student_id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=617354 DEFAULT CHARSET=utf8mb4 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='學生表'
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Serializable {

    private static final long serialVersionUID = 6712540741269055064L;

    private Integer studentId;
    private Integer age;
    private String name;
    private Integer sex;
    private Date createTime;
    private Integer status;
}

第三步:配置數據庫鏈接信息github

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/simple_fast
    username: root
    password: root

增刪改查

@Mapper
public interface StudentMapper {

    @Select("select * from student where student_id = #{studentId}")
    Student findById(@Param("studentId") Integer studentId);

    @Insert("insert into student(age,name) values(#{age},#{name})")
    int addStudent(@Param("name") String name,@Param("age") Integer age);

    @Update("update student set name = #{name} where student_id = #{studentId}")
    int updateStudent(@Param("studentId") Integer studentId,@Param("name") String name);

    @Delete("delete from student where student_id = #{studentId}")
    int deleteStudent(@Param("studentId") Integer studentId);
}

上面演示的傳參方式是經過單個參數傳遞的,若是想經過Map或實體類傳參數,就不須要使用@Param來綁定參數了,將map中的key或者實體類中的屬性與sql中的參數值對應上就能夠了redis

經過XML配置完成數據操做

@Mapper和@MapperScanspring

@Mapper加在數據層接口上,將其註冊到ioc容器上,@MapperScan加在啓動類上,須要指定掃描的數據層接口包。以下:sql

@Mapper
public interface StudentMapper {}
@SpringBootApplication
@MapperScan("com.javatrip.mybatis.mapper")
public class MybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}

兩個註解的做用同樣,在開發中爲了方便,一般咱們會使用@MapperScan。數據庫

指定mapper.xml的位置緩存

mybatis:
  mapper-locations: classpath:mybatis/*.xml

開啓數據實體映射駝峯命名微信

mybatis:
  configuration:
    map-underscore-to-camel-case: true

編寫xml和與之對應的mapper接口

<?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.javatrip.mybatis.mapper.StudentXMapper">
    <select id="findById" resultType="com.javatrip.mybatis.entity.Student">
        select * from student where student_id = #{studentId}
    </select>
    <insert id="addStudent" parameterType="com.javatrip.mybatis.entity.Student">
        insert into student(name,age) values(#{name},#{age})
    </insert>
    
    <update id="updateStudent" parameterType="com.javatrip.mybatis.entity.Student">
        update student set name = #{name} where  student_id = #{studentId}
    </update>

    <delete id="deleteStudent" parameterType="Integer">
        delete from student where student_id = #{studentId}
    </delete>
</mapper>
@Mapper
public interface StudentXMapper {

    Student findById(@Param("studentId") Integer studentId);

    int addStudent(Student student);

    int updateStudent(@Param("studentId") Integer studentId,@Param("name") String name);

    int deleteStudent(@Param("studentId") Integer studentId);
}

編寫測試類

@SpringBootTest
class MybatisApplicationTests {

    @Autowired
    StudentMapper mapper;

    @Autowired
    StudentXMapper xMapper;

    @Test
    void testMapper() {

        Student student = mapper.findById(10);
        mapper.addStudent("Java旅途",19);
        mapper.deleteStudent(31);
        mapper.updateStudent(10,"Java旅途");
    }

    @Test
    void contextLoads() {
        
        Student student = xMapper.findById(10);
        Student studentDo = new Student();
        studentDo.setAge(18);
        studentDo.setName("Java旅途呀");
        xMapper.addStudent(studentDo);
        xMapper.deleteStudent(32);
        xMapper.updateStudent(31,"Java旅途");
    }
}

這裏有幾個須要注意的點:mapper標籤中namespace屬性對應的是mapper接口;select標籤的id對應mapper接口中的方法名字;select標籤的resultType對應查詢的實體類,使用全路徑。


本文示例代碼已上傳至github,點個star支持一下!

Spring Boot系列教程目錄

spring-boot-route(一)Controller接收參數的幾種方式

spring-boot-route(二)讀取配置文件的幾種方式

spring-boot-route(三)實現多文件上傳

spring-boot-route(四)全局異常處理

spring-boot-route(五)整合Swagger生成接口文檔

spring-boot-route(六)整合JApiDocs生成接口文檔

spring-boot-route(七)整合jdbcTemplate操做數據庫

spring-boot-route(八)整合mybatis操做數據庫

spring-boot-route(九)整合JPA操做數據庫

spring-boot-route(十)多數據源切換

spring-boot-route(十一)數據庫配置信息加密

spring-boot-route(十二)整合redis作爲緩存

spring-boot-route(十三)整合RabbitMQ

spring-boot-route(十四)整合Kafka

spring-boot-route(十五)整合RocketMQ

spring-boot-route(十六)使用logback生產日誌文件

spring-boot-route(十七)使用aop記錄操做日誌

spring-boot-route(十八)spring-boot-adtuator監控應用

spring-boot-route(十九)spring-boot-admin監控服務

spring-boot-route(二十)Spring Task實現簡單定時任務

spring-boot-route(二十一)quartz實現動態定時任務

spring-boot-route(二十二)實現郵件發送功能

spring-boot-route(二十三)開發微信公衆號

這個系列的文章都是工做中頻繁用到的知識,學完這個系列,應付平常開發綽綽有餘。若是還想了解其餘內容,掃面下方二維碼告訴我,我會進一步完善這個系列的文章!

相關文章
相關標籤/搜索