首頁>技術>

前言

Mybatis是很多Java開發者都在使用的一款ORM框架,它內部封裝了JDBC,我們使用它不需要再花時間去寫一些載入驅動,建立連線,關閉連線的程式碼。

如何在Spring Boot專案中使用Mybatis?

Spring Boot 整合Mybatis也是非常簡單的,Spring已經為我們提供了整合Mybatis的元件。

<properties><java.version>1.8</java.version><mybatis.spring.boot.version>2.1.2</mybatis.spring.boot.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>${mybatis.spring.boot.version}</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>

接下來我們使用idea-mybatis-generatorc外掛來生成程式碼

package com.example.demo.entity;import java.io.Serializable;/*** user* @author */public class User implements Serializable {private Long id;private String username;private String password;private Integer age;private static final long serialVersionUID = 1L;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 String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}}
package com.example.demo.mapper;import com.example.demo.entity.User;public interface UserMapper {int deleteByPrimaryKey(Long id);int insert(User record);int insertSelective(User record);User selectByPrimaryKey(Long id);int updateByPrimaryKeySelective(User record);int updateByPrimaryKey(User record);}
<?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.example.demo.mapper.UserMapper"><resultMap id="BaseResultMap" type="com.example.demo.entity.User"><id column="id" jdbcType="BIGINT" property="id" /><result column="username" jdbcType="VARCHAR" property="username" /><result column="password" jdbcType="VARCHAR" property="password" /><result column="age" jdbcType="INTEGER" property="age" /></resultMap><sql id="Base_Column_List">id, username, `password`, age</sql><select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">select <include refid="Base_Column_List" />from userwhere id = #{id,jdbcType=BIGINT}</select><delete id="deleteByPrimaryKey" parameterType="java.lang.Long">delete from userwhere id = #{id,jdbcType=BIGINT}</delete><insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.example.demo.entity.User" useGeneratedKeys="true">insert into user (username, `password`, age)values (#{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})</insert><insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.example.demo.entity.User" useGeneratedKeys="true">insert into user<trim prefix="(" suffix=")" suffixOverrides=","><if test="username != null">username,</if><if test="password != null">`password`,</if><if test="age != null">age,</if></trim><trim prefix="values (" suffix=")" suffixOverrides=","><if test="username != null">#{username,jdbcType=VARCHAR},</if><if test="password != null">#{password,jdbcType=VARCHAR},</if><if test="age != null">#{age,jdbcType=INTEGER},</if></trim></insert><update id="updateByPrimaryKeySelective" parameterType="com.example.demo.entity.User">update user<set><if test="username != null">username = #{username,jdbcType=VARCHAR},</if><if test="password != null">`password` = #{password,jdbcType=VARCHAR},</if><if test="age != null">age = #{age,jdbcType=INTEGER},</if></set>where id = #{id,jdbcType=BIGINT}</update><update id="updateByPrimaryKey" parameterType="com.example.demo.entity.User">update userset username = #{username,jdbcType=VARCHAR},`password` = #{password,jdbcType=VARCHAR},age = #{age,jdbcType=INTEGER}where id = #{id,jdbcType=BIGINT}</update></mapper>

編寫service。

package com.example.demo.service;import com.example.demo.entity.User;public interface UserService {void add(User user);}
package com.example.demo.service.impl;import com.example.demo.entity.User;import mapper.UserMapper;import org.springframework.stereotype.Service;import com.example.demo.service.UserService;import javax.annotation.Resource;@Servicepublic class UserServiceImpl implements UserService {    @Resource    private UserMapper userMapper;    @Override    public void add(User user) {        userMapper.insert(user);    }}

編寫Controller和返回類。

package com.example.demo.util;public enum ResultCode {SUCCESS("200", "成功"),ERROR("500", "失敗");private String code;private String message;ResultCode(String code, String message) {this.code = code;this.message = message;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}
package com.example.demo.util;public class Result {private String code;private String message;private Object data;public Result() {this.setCode(ResultCode.SUCCESS.getCode());this.setMessage(ResultCode.SUCCESS.getMessage());}public Result(Object data) {this.setCode(ResultCode.SUCCESS.getCode());this.setMessage(ResultCode.SUCCESS.getMessage());this.setData(data);}public Result(String code, String message) {this.setCode(code);this.setMessage(message);}public Result(String code) {this.setCode(code);this.setMessage(ResultCode.ERROR.getMessage());}public static Result Success() {return new Result();}public static Result Success(Object data) {return new Result(data);}public static Result Error() {return new Result(ResultCode.ERROR.getCode(), Result.Error().getMessage());}public static Result Error(String message) {return new Result(message);}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}}
package com.example.demo.controller;import com.example.demo.entity.User;import org.mybatis.spring.annotation.MapperScan;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.example.demo.service.UserService;import com.example.demo.util.Result;import javax.annotation.Resource;@RestController@RequestMapping("api/user")@MapperScan("com.example.demo.mapper")public class UserController {@Resourceprivate UserService userService;@PostMappingpublic Result add(@RequestBody User user) {userService.add(user);return Result.Success();}}

接下來我們來測試一下。

請求成功,SpringBoot和Mybatis的整合就完成了。

Demo地址:https://gitee.com/123343411413/demo.git

10
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 33-Spring MVC的REST控制器建言