Spring boot整合Mybatis


  時隔兩個月的再來寫博客的感覺怎么樣呢,只能用“棒”來形容了。閑話少說,直接入正題,之前的博客中有說過,將spring與mybatis整個后開發會更爽,基於現在springboot已經成為整個業界開發主流框架的情況下,今天在這里就直接將mybatis整合spring boot了。

  先簡單地提一下Spring boot。在Mybatis還沒火起來之前,大家用的是SSH(Struts2+Spring+Hibernate),之后mybatis以其小巧輕便的優點成為中小型項目的首選,與此同時基於Spring的自家mvc框架SpringMVC也火起來了,於是開發的框架又成了SSM(SpringMVC+Spring+Mybatis),但是Spring和Spring MVC本是同源,叫起來還得分開叫真是頭疼,然后Spring boot出現了,它是基於Spring4的條件注冊的一套快速開發整合包,同時又整合了Spring MVC了,所以說SpringMVC的那一套注解可以原封不動地搬來用。同時Spring boot為了解決Spring框架需要進行大量的配置的問題又引入自動配置的概念,也就是說能用注解我絕不用配置文件。關於Spring boot具體一點的東西我就直接在下面結合代碼里講了。

  首先呢,新建一個maven項目,記得勾選上create a simple project

之后的Group id、Artifact Id之類的就可以隨便填了,以下是我建好的項目結構

項目建好后第一件事,添加依賴

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
         <dependency> 
             <groupId>org.mybatis.spring.boot</groupId> 
             <artifactId>mybatis-spring-boot-starter</artifactId> 
             <version>1.3.2</version> 
         </dependency>
         <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

解釋一下幾個關鍵的包

  • spring-boot-starter-parent:項目可以通過繼承spring-boot-starter-parent包來獲得一些合理的默認配置,在在dependencies里的部分配置可以不用填寫version信息,自動繼承parent包的版本,當然也可以不用。
  • spring-boot-starter:這是Spring Boot的核心啟動器,包含了自動配置、日志和YAML。
  • spring-boot-starter-web:構建Web,包含RESTful風格框架SpringMVC和默認的嵌入式容器Tomcat,就是這個包整合了Spring mvc,同時自帶嵌入式tomcat意味着我們啟動項目時就只要運行main方法就行,不用再跑eclipse上自帶的tomcat了
  • mybatis-spring-boot-starter:這個就沒什么好說的,官方提供的spring boot和mybatis的整合包。

包導完之后我的習慣是先把整個項目的包結構搭建起來

 

然后在最外層的包里面寫啟動類,老規矩先貼代碼

package com.fiberhome;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

這里只有一個注解@SpringBootApplication,但是作用卻大得驚人,control鍵然后點擊該注解看源碼可知它替代了@@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan這三個注解的功能。接下來解釋這個三個注解的作用,理解了這三個注解,自然理解了@SpringBootApplication。

  • @SpringBootConfiguration:該注解繼承自@Configuration,一般與@Bean配合使用,使用這兩個注解就可以創建一個簡單的spring配置類,可以用來替代相應的xml配置文件。
  • @EnableAutoConfiguration:該注解的意思就是Springboot可以根據你添加的jar包來配置你項目的默認配置,比如當你添加了mvc的jar包,它就會自動配置web項目所需的配置
  • @ComponentScan:顧名思義該注解是用來掃描組件的,只要組件上有@component及其子注解@Service、@Repository、@Controller等,springboot會自動掃描到並納入Spring 容器進行管理,有點類似xml文件中的<context:component-scan>,該注解不填屬性的話就是默認掃描啟動類所在的包,或者啟動類所在包的下一級,所以啟動類要放在最外層

緊接着把我的實體類(User.java)代碼貼出來

package com.fiberhome.pojo;

import org.springframework.stereotype.Component;

@Component
public class User {

    private Long id;
    private String username;
    private int age;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }    
}

然后我們從底層的代碼寫起,先是mapper接口

package com.fiberhome.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.fiberhome.pojo.User;
@Mapper
public interface UserMapper {

    //獲取用戶名單
    public List<User> getUser() throws Exception;
    //根據id刪除用戶
    public void deleteUser(int id)throws Exception;
    //新增用戶
    public void addUser(User user)throws Exception;
}

然后是對應該mapper接口的user.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://www.mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fiberhome.mapper.UserMapper">
    <select id="getUser" resultType="com.fiberhome.pojo.User">
        select * from user
    </select>
    <delete id="deleteUser" parameterType="Integer">
        delete from user where id =#{id}
    </delete>
    <insert id="addUser" parameterType="com.fiberhome.pojo.User">
        insert into user(id,username,age)values(#{id},#{username},#{age})
    </insert>
</mapper>

緊接着是Service層的代碼

UserService.java

package com.fiberhome.service;

import java.util.List;
import com.fiberhome.pojo.User;

public interface UserService {
    //顯示所有用戶
    public List<User>getUser()throws Exception;
    //根據id刪除用戶
    public void deleteUser(int id)throws Exception;
    //新增用戶
    public void addUser(User user)throws Exception;
}

UserServiceImpl.java

package com.fiberhome.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fiberhome.mapper.UserMapper;
import com.fiberhome.pojo.User;
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> getUser() throws Exception {
        return userMapper.getUser();
    }
    //根據id刪除用戶
    @Override
    public void deleteUser(int id) throws Exception {
        userMapper.deleteUser(id);
    }
    //新增用戶
    @Override
    public void addUser(User user) throws Exception {
        userMapper.addUser(user);
    }
}

最后是Controller代碼

package com.fiberhome.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fiberhome.pojo.User;
import com.fiberhome.service.UserService;

@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private User user;
    //顯示用戶
    @RequestMapping("list")
    public List<User> index() throws Exception {
        return userService.getUser();
    }
    //刪除用戶
    @RequestMapping("delete/{id}")
    public String delete(@PathVariable int id) throws Exception {
        userService.deleteUser(id);
        return "你已經刪掉了id為"+id+"的用戶";
    }
    //增加用戶
    @RequestMapping("addUser")
    public String addUser() throws Exception {
        user.setAge(33);
        user.setUsername("阿花");
        userService.addUser(user);
        return "增加用戶";
    }
}

以上代碼已經寫得很明白了,也沒什么可解釋的。值得注意的是為了將mapper裝配到spring容器中去,要在mapper接口中加上@Mapper注解,或者在啟動類中加上@MapperScan(“包路徑”)注解。到了這里基本完工了,還差一個application.properties文件,用於存放數據庫連接信息和mapper.xml文件位置

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
mybatis.mapper-locations: classpath:mapper/*.xml

 運行的時候只需運行啟動類的main方法即可,由於springboot嵌入了tomcat,所以項目跑起來后tomcat會自啟。

到這里mybatis和springboot就整合完了,有人可能會想,既然省了這么多xml文件,有沒有方法可以連user.xml文件一起省了,答案是當然有了,接下來我還會帶來mybatis注解開發,敬請期待。。。

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM