1. 程式人生 > >spring boot 整合mybatis

spring boot 整合mybatis

參考 plugins odin system stack name incr xmlns xsd

參考: http://blog.csdn.net/saytime/article/details/74783296

spring boot可以使用全註解的方式進行開發,極大的提高了開發效率,為越來越多的公司所使用,

mybatis允許開發者使用sql語句,使開發更具靈活性。下面講一下如何將spring boot 和mybatis整合起來

0:準備數據

  

CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT ID,
  `username` varchar(50) NOT NULL COMMENT 用戶名,
  `age` 
int(11) NOT NULL COMMENT 年齡, `ctm` datetime NOT NULL COMMENT 創建時間, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES(張三, 18, NOW()) ;
INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES(李四, 20, NOW()) ;


1:首先創建maven工程,工程目錄結構圖如下:springBootDemo1

技術分享圖片


2:添加springboot 的工程依賴pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.liyafei</groupId>
<artifactId>springBootDemo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<properties>
<webVersion>3.1</webVersion>
<mybatis-spring-boot.version>1.2.0</mybatis-spring-boot.version>
</properties>

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <!-- Spring-Mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <!-- Add typical dependencies for a web application --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> </dependencies> <build> <!-- 將工程打包成可執行jar文件 --> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>


3: 為工程添加配置文件applIcation.yml

  application.yml

spring:  //數據源
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/demo
    username: root
    password: 1367356

mybatis:   //配置mybatis
  mapper-locations: classpath:mybatis/mapper/*.xml   Mapper所在的配置文件路徑,進行掃描
  config-location: classpath:mybatis/mybatis-config.xml   mybaits-config文件
  type-aliases-package: com.liyafei.dao.pojo  <!-- pojo所在的包,與表一一對應-->

UserMapper.xml

<?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.liyafei.dao.mapper.UserMapper" >
    <resultMap id="BaseResultMap" type="com.liyafei.dao.pojo.User" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="username" property="username" jdbcType="VARCHAR" />
        <result column="age" property="age" jdbcType="INTEGER" />
        <result column="ctm" property="ctm" jdbcType="TIMESTAMP"/>
    </resultMap>

    <sql id="Base_Column_List" >
        id, username, age, ctm
    </sql>

    <select id="getUserList" resultMap="BaseResultMap"  >
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_user
    </select>

    <select id="getUserById" parameterType="java.lang.Integer" resultMap="BaseResultMap" >
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_user
        WHERE id = #{id}
    </select>

    <insert id="add" parameterType="com.liyafei.dao.pojo.User" >
        INSERT INTO
        tb_user
        (username,age,ctm)
        VALUES
        (#{username}, #{age}, now())
    </insert>

    <update id="update" parameterType="java.util.Map" >
        UPDATE
        tb_user
        SET
        username = #{user.username},age = #{user.age}
        WHERE
        id = #{id}
    </update>

    <delete id="delete" parameterType="java.lang.Integer" >
        DELETE FROM
        tb_user
        WHERE
        id = #{id}
    </delete>
</mapper>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
    </typeAliases>
</configuration>


4:創建dao層類

public class User {
	private int id;
	private String username;
	private int age;
	private Date ctm;
    }

package com.liyafei.dao.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import com.liyafei.dao.pojo.User;

@Repository
public interface UserMapper {

    User getUserById(Integer id);

    public List<User> getUserList();

    public int add(User user);

    public int update(@Param("id") Integer id, @Param("user") User user);

    public int delete(Integer id);

}

5:創建service層

package com.liyafei.service;

import java.util.List;

import com.liyafei.dao.pojo.User;

public interface UserService {

	User getUserById(Integer id);

	public List<User> getUserList();

	public int add(User user);

	public int update(Integer id, User user);

	public int delete(Integer id);

}

package com.liyafei.service;

import java.util.List;

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

import com.liyafei.dao.mapper.UserMapper;
import com.liyafei.dao.pojo.User;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
	private UserMapper userMapper;


	public User getUserById(Integer id) {
		return userMapper.getUserById(id);
	}


	public List<User> getUserList() {
		return userMapper.getUserList();
	}


	public int add(User user) {
		return userMapper.add(user);
	}

	public int update(Integer id, User user) {
		return userMapper.update(id, user);
	}

	public int delete(Integer id) {
		return userMapper.delete(id);
	}


}

6:創建controller層

  

package com.liyafei.controller;

import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.liyafei.dao.pojo.User;
import com.liyafei.service.UserService;
import com.liyafei.util.JsonResult;

@RestController
public class UserController {

	@Autowired
	private UserService userService;

	/**
	 * ????ID??????
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "user/{id}", method = RequestMethod.GET)
	public ResponseEntity<JsonResult> getUserById (@PathVariable(value="id") String id){
	//@ResponseBody
	//public String getUserById (@PathVariable(value="id") String id){
		System.out.println(id);
		JsonResult r = new JsonResult();
		int id1=Integer.parseInt(id);
		try {
			User user = userService.getUserById(id1);
			r.setResult(user);
			r.setStatus("ok");
		} catch (Exception e) {
			r.setResult(e.getClass().getName() + ":" + e.getMessage());
			r.setStatus("error");
			e.printStackTrace();
		}
		//return "hello world";
		return ResponseEntity.ok(r);
	}

	
}

7:創建util工具類

  

package com.liyafei.util;

public class JsonResult {

    private String status = null;

    private Object result = null;

    public JsonResult status(String status) {
        this.status = status;
        return this;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Object getResult() {
        return result;
    }

    public void setResult(Object result) {
        this.result = result;
    }

}


8:創建主函數,主函數需位於根目錄下,與其同級的包將會被掃描

package com.liyafei;

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

@EnableAutoConfiguration
@SpringBootApplication
@MapperScan("com.liyafei.dao.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    
}


9:啟動工程,進行測試,成功。

技術分享圖片

spring boot 整合mybatis