spring boot 之 mybatis 集成

1、使用idea创建spring boot 项目

spring boot 之 mybatis 集成

spring boot 之 mybatis 集成

创建后查看项目中的pom文件中是否有(正常情况下都会有,如果没有的话自己手动加):

org.mybatis.spring.boot

mybatis-spring-boot-starter

1.3.2

我链接的是mysql数据库依赖如下(正常情况下都会有,如果没有的话自己手动加):

mysql

mysql-connector-java

runtime

2、application.yml配置文件,配置数据库与mybatis

spring boot 之 mybatis 集成

3、添加controller,Controller记得添加@RestController注解代码如下:

package com.example.demo.controller;

import com.example.demo.business.testService;

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

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

import java.util.List;

@RestController

@RequestMapping("/demo/srv")

public class testController {

@Autowired

testService service;

@RequestMapping(value="/test", method = RequestMethod.GET)

public List test() throws Exception {

try {

List list = service.getDiaryList();

return list;

}

catch (Exception ex)

{

throw ex;

}

}

}

4、添加Service,注意@Service注解加在实现类中代码如下:

package com.example.demo.business;

import java.util.HashMap;

import java.util.List;

public interface testService {

List getDiaryList() throws Exception;

}

package com.example.demo.business;

import com.example.demo.access.testDao;

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

import org.springframework.stereotype.Service;

import java.util.HashMap;

import java.util.List;

@Service("testService")

public class testServiceImpl implements testService {

@Autowired

testDao dao;

@Override

public List getDiaryList() throws Exception {

return dao.getDiaryList();

}

}

5、添加Dao Dao层需要加@Mapper注解,代码如下:

package com.example.demo.access;

import org.apache.ibatis.annotations.Mapper;

import java.util.HashMap;

import java.util.List;

@Mapper

public interface testDao {

List getDiaryList() throws Exception;

}

6、添加xml:

spring boot 之 mybatis 集成