3 springboot集成mybatis和全局异常捕获

mybatis有两种方式,一种是基于XML,一种是基于注解

springboot集成mybatis

首先先创建表,这里都简化了

  DROP TABLE IF EXISTS `user`;
  CREATE TABLE `user` (
    `id` int(11) NOT NULL auto_increment,
    `username` varchar(255) default NULL,
    PRIMARY KEY  (`id`)
  ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
  
  INSERT INTO `user` VALUES ('1', 'lijia');

然后创建maven项目,在pom.xml中添加


    org.springframework.boot
    spring-boot-parent
    1.5.4.RELEASE



    
    1.8
    UTF-8
    UTF-8




    
        org.springframework.boot
        spring-boot-starter-web
    

    
        org.mybatis.spring.boot
        mybatis-spring-boot-starter
        1.3.0
    
    
        mysql
        mysql-connector-java
        runtime
    

    
        org.springframework.boot
        spring-boot-devtools
        true
    

    
        com.alibaba
        fastjson
        1.2.31
    

    
        org.projectlombok
        lombok
        provided
    




    
        
            org.springframework.boot
            spring-boot-maven-plugin
            
                true
            
        
    

XML形式

目录结构是

3 springboot集成mybatis和全局异常捕获_第1张图片

application.properties

# jdbc_config
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://172.16.255.69:3306/test?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root


# Mybatis
#mybatis.typeAliasesPackage对应的是实体类位置
mybatis.typeAliasesPackage=org.lijia.bean
#mybatis.mapperLocations查找mybatis配置文件位置
mybatis.mapperLocations=classpath:mybatis/*.xml

实体类User

public class User {
    private String id;      //用户id
    private String username;    //用户名
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}

HelloController :

import com.alibaba.fastjson.JSON;
import com.lijia.bean.User;
import com.lijia.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/hello")
public class HelloController { 
    @Autowired
    private HelloService helloService;

    @RequestMapping("/get")
    @ResponseBody
    public String get(@RequestParam String username){
        User user = helloService.get(username);
        if(user!=null){
            System.out.println("user.getName():"+user.getUsername());
        }
        return JSON.toJSONString(user);

    }
    @RequestMapping("/exception")
    @ResponseBody
    public String exception(){
        throw new RuntimeException();
    }
}

HelloService :

import com.lijia.bean.User;
import com.lijia.dao.HelloMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
//@Transactional
public class HelloService {
    @Autowired
    private HelloMapper helloMapper;
    public User get(String username) {

        return  helloMapper.findUserByName(username);
    }
}

接口HelloMapper :

import com.lijia.bean.User;
public interface HelloMapper {
    public User findUserByName(String username);
}

mybatis配置文件:






    
        
        
    
    
    

最后启动类Application:

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.lijia.dao") //扫描接口
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

启动Application,输入成功获取数据


mybatis注解方式

注解方式我感觉太简单了,一般我也是用这个

3 springboot集成mybatis和全局异常捕获_第2张图片

没有了mybatis那些配置文件
application.properties:去除了mybatis的东西

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://172.16.255.69:3306/test?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

启动类Application:也没有了扫描

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);
    }
}

最主要的是:HelloMapper

import com.lijia.bean.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface HelloMapper {

    @Select("select * from user where username = #{username}")
    public User findUserByName(String username);
}

在接口上加上@Mapper
在方法上面加上@Select里面跟着sql
然后启动Application,结果一样


全局异常捕获

只要在项目中加上这个类

import com.lijia.common.result.Result;
import com.lijia.common.result.ResultEnum;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Desc:全局异常捕获并返回
 *
 */

@RestController
@ControllerAdvice
public class ExceptionHandlerController {

    @ExceptionHandler(Exception.class)
    public Result defaultExceptionHandler(HttpServletRequest request, Exception e)
            throws Exception {
        return new Result<>(ResultEnum.SERVER_ERROR, e.getMessage());
    }
}

这里面的Result是自定义。

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@NoArgsConstructor
public class Result {
    private int code;
    private String desc;
    private T data;

    public Result(ResultEnum resultEnum) {
        this.code = resultEnum.getCode();
        this.desc = resultEnum.getDesc();
    }

    public Result(ResultEnum resultEnum, T data) {
        this.code = resultEnum.getCode();
        this.desc = resultEnum.getDesc();
        this.data = data;
    }
}

还有个枚举

public enum ResultEnum {
    SUCCESS(200, "success"), SERVER_ERROR(500, "server error");

    private int code;
    private String desc;

    ResultEnum(int code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    public int getCode() {
        return code;
    }

    public String getDesc() {
        return desc;
    }
}

在上面的Controller中已经有异常的方法,启动Application

3 springboot集成mybatis和全局异常捕获_第3张图片

代码放在
https://github.com/lijiaccy/springbootmybatis.git

你可能感兴趣的:(3 springboot集成mybatis和全局异常捕获)