Spring boot整合Mybatis

  时隔两个月的再来写博客的感受怎么样呢,只能用“棒”来形容了。闲话少说,直接入正题,以前的博客中有说过,将spring与mybatis整个后开发会更爽,基于如今springboot已经成为整个业界开发主流框架的状况下,今天在这里就直接将mybatis整合spring boot了。java

  先简单地提一下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具体一点的东西我就直接在下面结合代码里讲了。mysql

  首先呢,新建一个maven项目,记得勾选上create a simple project
web

以后的Group id、Artifact Id之类的就能够随便填了,如下是我建好的项目结构spring

项目建好后第一件事,添加依赖sql

  <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的整合包。

包导完以后个人习惯是先把整个项目的包结构搭建起来apache

 

而后在最外层的包里面写启动类,老规矩先贴代码tomcat

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。springboot

  • @SpringBootConfiguration:该注解继承自@Configuration,通常与@Bean配合使用,使用这两个注解就能够建立一个简单的spring配置类,能够用来替代相应的xml配置文件。
  • @EnableAutoConfiguration:该注解的意思就是Springboot能够根据你添加的jar包来配置你项目的默认配置,好比当你添加了mvc的jar包,它就会自动配置web项目所需的配置
  • @ComponentScan:顾名思义该注解是用来扫描组件的,只要组件上有@component及其子注解@Service、@Repository、@Controller等,springboot会自动扫描到并归入Spring 容器进行管理,有点相似xml文件中的<context:component-scan>,该注解不填属性的话就是默认扫描启动类所在的包,或者启动类所在包的下一级,因此启动类要放在最外层

紧接着把个人实体类(User.java)代码贴出来mybatis

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注解开发,敬请期待。。。

相关文章
相关标签/搜索