小白的springboot之路(三)、集成mybatis与MySQL

时间:2023-03-10 04:17:37
小白的springboot之路(三)、集成mybatis与MySQL

0、前言

  mybatis属于半自动的ORM,相比hibernate这种全自动的ORM,兼顾了性能与易用;目前企业项目中,基本都是mybatis的天下;今天就来整合mybatis与MySQL;

1、整合

  1.-1、添加依赖:

        <!-- 集成mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>

1-2、创建数据表:

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(32) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`userName` varchar(32) NOT NULL COMMENT '用户名称',
`passWord` varchar(50) NOT NULL COMMENT '用户密码',
`realName` varchar(32) DEFAULT NULL COMMENT '中文名字',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('', 'anson', '', '张三');
INSERT INTO `user` VALUES ('', 'Alex', '', '李四');
INSERT INTO `user` VALUES ('', 'kks', '', '王五');

1-3、增加实体类User.java

package com.anson.model;

public class User {
private Integer id;
private String username;
private String password;
private String realname;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname == null ? null : realname.trim();
}
}

1-4、增加Mapper接口UserMapper.java;注意添加@Repository注解

package com.anson.dao;

import com.anson.model.User;
import org.springframework.stereotype.Repository; @Repository //添加Repository注解
public interface UserMapper {
int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record);
}

1-5、添加Mapper对应的XML文件UserMapper.xml,注意<mapper namespace="com.anson.dao.UserMapper">对应Mapper包

<?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.anson.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.anson.model.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="userName" jdbcType="VARCHAR" property="username" />
<result column="passWord" jdbcType="VARCHAR" property="password" />
<result column="realName" jdbcType="VARCHAR" property="realname" />
</resultMap>
<sql id="Base_Column_List">
id, userName, passWord, realName
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.anson.model.User">
insert into user (id, userName, passWord,
realName)
values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{realname,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.anson.model.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="username != null">
userName,
</if>
<if test="password != null">
passWord,
</if>
<if test="realname != null">
realName,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="realname != null">
#{realname,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.anson.model.User">
update user
<set>
<if test="username != null">
userName = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
passWord = #{password,jdbcType=VARCHAR},
</if>
<if test="realname != null">
realName = #{realname,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.anson.model.User">
update user
set userName = #{username,jdbcType=VARCHAR},
passWord = #{password,jdbcType=VARCHAR},
realName = #{realname,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>

1-6、编写service接口UserService.java:

package com.anson.service;

import com.anson.model.User;

public interface UserService
{
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}

编写接口实现类UserServiceImpl.java,注意增加@Service注解:

package com.anson.service.Impl;

        import com.anson.dao.UserMapper;
import com.anson.model.User;
import com.anson.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; /**
* @description: service实现类
* @author: anson
* @Date: 2019/9/5 0:37
* @version: 1.0
*/
@Service
public class UserServiceImpl implements UserService
{
@Autowired
UserMapper usermapper; @Override
public User selectByPrimaryKey(Integer id)
{
return usermapper.selectByPrimaryKey(id);
}
@Override
public int deleteByPrimaryKey(Integer id)
{
return usermapper.deleteByPrimaryKey(id);
}
@Override
public int insert(User record)
{
return usermapper.insert(record);
}
@Override
public int insertSelective(User record)
{
return usermapper.insertSelective(record);
}
@Override
public int updateByPrimaryKeySelective(User record)
{
return usermapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(User record)
{
return usermapper.updateByPrimaryKey(record);
} }

1-7、编写controller:

package com.anson.controller;

import com.anson.model.User;
import com.anson.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
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; /**
* @description: TODO
* @author: anson
* @Date: 2019/9/5 0:42
* @version: 1.0
*/ @RestController
@Api(value = "用户接口")
@RequestMapping("/user")
public class UserController
{
@Autowired
private UserService userservice; @ApiOperation(value = "获取用户", notes = "根据id查询用户信息")
@ApiImplicitParam(name = "id", value = "用户id", required=true, dataType="int") //API参数
@RequestMapping(value="/getUserById/{id}",method= RequestMethod.GET)
public User selectByPrimaryKey(@PathVariable int id)
{
return userservice.selectByPrimaryKey(id);
}
}

1-8、启动类中增加包扫描注解:

@SpringBootApplication
@MapperScan("com.anson.dao") //增加Mapper包扫描注解
public class application
{
public static void main(String[] args)
{
SpringApplication.run(application.class,args);
}
}

1-9、配置文件中增加数据源和mybatis的注解:

#服务器配置
server.port=8090 #mysql数据源配置
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password =88888888 #mybatis配置
mybatis.type-aliases-package=com.anson.model
mybatis.mapperLocations=classpath:mapper/*Mapper.xml #showSql
logging.level.com.anson.dao=debug

好了,完毕,运行,可以在swagger中查看和运行接口:

小白的springboot之路(三)、集成mybatis与MySQL

小白的springboot之路(三)、集成mybatis与MySQL

可以看到已经正常运行了;

好了,本节到此为止,下节将讲介绍mybatis-generator自动生成实体、mapper和mapper对应的XML

源码地址:https://github.com/anson-yang/cloverDemo.git