SpringBoot (five) SpringBoot integration mybatis

A: Project structure:

 

 

 

 

 

Two : pom file as follows:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.0.4.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>
        <!-- jdbcTemplate -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
         
        <!-- MySQL连接 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- Add typical dependencies for a web application -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
  </dependencies> 

Three: database configuration:

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.1.20:3306/test
    username: root
    password: root123

Four: Code Description:

The most troublesome mybati started, various configuration files, the entity class, association dao layer mapping, there is a big push other configurations. Of course, also we found that mybatis drawbacks, early in the development of automated production generator entity class may result Table, profile codes, and dao layer, part of the developer amount can be reduced; later also a lot of optimization may be used annotated.

So are two ways to introduce a no configuration notes edition, version profile

1. No configuration file annotation version
added profiles
----------------

实体类User.class

package cn.saytime.bean;
 
import java.util.Date;
 
/**
 * @ClassName cn.saytime.bean.User
 * @Description
 * @date 2017-07-04 22:47:28
 */
public class User {
 
    private int id;
    private String username;
    private int age;
    private Date ctm;
 
    public User() {
    }
 
    public User(String username, int age) {
        this.username = username;
        this.age = age;
        this.ctm = new Date();
    }
 
    // Getter、Setter

 

Package cn.saytime.mapper; 
 
Import cn.saytime.bean.User;
 Import org.apache.ibatis.annotations.Delete;
 Import org.apache.ibatis.annotations.Insert;
 Import org.apache.ibatis.annotations.Param;
 Import org.apache.ibatis.annotations.Select;
 Import org.apache.ibatis.annotations.Update; 
 
Import java.util.List; 
 
// @Mapper @Mapper annotation can be used here, but each mapper are annotated too much trouble, so @MapperScan unified configuration in the scan path in the application class 
public  interface UserMapper { 
 
    @Select ( "the SELECT * the FROM tb_user the WHERE ID = # {ID}" ) 
    the User getUserById (ID Integer); 
 
    @Select ("SELECT * FROM tb_user")
    public List<User> getUserList();
 
    @Insert("insert into tb_user(username, age, ctm) values(#{username}, #{age}, now())")
    public int add(User user);
 
    @Update("UPDATE tb_user SET username = #{user.username} , age = #{user.age} WHERE id = #{id}")
    public int update(@Param("id") Integer id, @Param("user") User user);
 
    @Delete("DELETE from tb_user where id = #{id} ")
    public int delete(Integer id);

————————————————
UserService.class

package cn.saytime.service;
 
import cn.saytime.bean.User;
import org.springframework.stereotype.Service;
 
import java.util.List;
 
/**
 * @ClassName cn.saytime.service.UserService
 * @Description
 */
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);

UserServiceimpl.class

package cn.saytime.service.impl;
 
import cn.saytime.bean.User;
import cn.saytime.mapper.UserMapper;
import cn.saytime.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.List;
 
/**
 * @ClassName cn.saytime.service.impl.UserServiceImpl
 * @Description
 */
@Service
public class UserServiceImpl implements UserService {
 
    @Autowired
    private UserMapper userMapper;
 
    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }
 
    @Override
    public List<User> getUserList() {
        return userMapper.getUserList();
    }
 
    @Override
    public int add(User user) {
        return userMapper.add(user);
    }
 
    @Override
    public int update(Integer id, User user) {
        return userMapper.update(id, user);
    }
 
    @Override
    public int delete(Integer id) {
        return userMapper.delete(id);
    }
}
JsonResult.class 通用json返回类:


package
cn.saytime.bean; public class JsonResult { private String status = null; private Object result = null; public JsonResult status(String status) { this.status = status; return this; } // Getter Setter

 

UserController.class(Restful风格)

package cn.saytime.web;
 
import cn.saytime.bean.JsonResult;
import cn.saytime.bean.User;
import cn.saytime.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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.RestController;
 
import java.util.List;
 
/**
 * @ClassName cn.saytime.web.UserController
 * @Description
 * @date 2017-07-04 22:46:14
 */
@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") Integer id){
        JsonResult r = new JsonResult();
        try {
            User user = userService.getUserById(id);
            r.setResult(user);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
 
    /**
     * 查询用户列表
     * @return
     */
    @RequestMapping(value = "users", method = RequestMethod.GET)
    public ResponseEntity<JsonResult> getUserList (){
        JsonResult r = new JsonResult();
        try {
            List<User> users = userService.getUserList();
            r.setResult(users);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
 
    /**
     * 添加用户
     * @param user
     * @return
     */
    @RequestMapping(value = "user", method = RequestMethod.POST)
    public ResponseEntity<JsonResult> add (@RequestBody User user){
        JsonResult r = new JsonResult();
        try {
            int orderId = userService.add(user);
            if (orderId < 0) {
                r.setResult(orderId);
                r.setStatus("fail");
            } else {
                r.setResult(orderId);
                r.setStatus("ok");
            }
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
 
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
 
    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @RequestMapping(value = "user/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") Integer id){
        JsonResult r = new JsonResult();
        try {
            int ret = userService.delete(id);
            if (ret < 0) {
                r.setResult(ret);
                r.setStatus("fail");
            } else {
                r.setResult(ret);
                r.setStatus("ok");
            }
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
 
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
 
    /**
     * 根据id修改用户信息
     * @param user
     * @return
     */
    @RequestMapping(value = "user/{id}", method = RequestMethod.PUT)
    public ResponseEntity<JsonResult> update (@PathVariable("id") Integer id, @RequestBody User user){
        JsonResult r = new JsonResult();
        try {
            int ret = userService.update(id, user);
            if (ret < 0) {
                r.setResult(ret);
                r.setStatus("fail");
            } else {
                r.setResult(ret);
                r.setStatus("ok");
            }
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
 
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
 
}
Application.java

package cn.saytime;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
@MapperScan("cn.saytime.mapper")
public class SpringbootMybaitsApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybaitsApplication.class, args);
    }

test:

Use PostMan tested:  HTTP: // localhost: 8080 / the User / 1

2. profile version

Join Profiles

 

 Code portions that compared to the above embodiment, only the profile change and the following sections UserMapper. Class

package cn.saytime.mapper;
 
import cn.saytime.bean.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
 
import java.util.List;
 
/**
 * @ClassName cn.saytime.mapper.UesrMapper
 * @Description
 */
@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);

}


UserServiceImpl类:

 

 
 

import java.util.List;

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

import org.springframework.stereotype.Service;

 
 

import com.demo.dao.UserDao;
import com.demo.mapper.User;
import com.demo.mapper.UserMapper1;
import com.demo.service.UserService;

 
 


@Service
public class UserServiceImpl implements UserService{

@Autowired
private UserDao userDao;

@Autowired
private UserMapper1 userMapper;

 
 

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

 
 

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

}

 
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>
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="cn.saytime.mapper.UserMapper" >
    <resultMap id="BaseResultMap" type="cn.saytime.bean.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="cn.saytime.bean.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>

 

Test method as above: HTTP: // localhost: 8080 / the User / 1

 

V. Brief Description:
I do not know you have not noticed it, is to introduce Springboot-mybatis dependent on time, spring is not the official starter, integrated springboot usual dependence, such as web, redis, etc., groupId and address artifactId as follows:

<dependency>
<the groupId> org.springframework.boot </ the groupId>
<the artifactId> Boot-spring-starter-Web </ the artifactId>
</ dependency>
and starter herein is dependent mybatis to provide a spring, so that the address is dependent on:

<dependency>
<the groupId> org.mybatis.spring.boot </ the groupId>
<the artifactId> MyBatis-Spring-Boot-Starter </ the artifactId>
<Version> 1.3.0 </ Version>
</ dependency>
and Notably here you must specify a version number, always use springboot reason why we do not need to specify the version number, because we introduced Maven Parent specified SpringBoot dependence, SpringBoot rely Pom official documents has been designated its own integrated third-party reliance the version number for Mybatis, Spring official did not provide their own starter, so must rely maven like normal, to increase the version number.
----------------

Guess you like

Origin www.cnblogs.com/2019lgg/p/11580718.html