spring boot 整合 mybatis
1、在pom.xml中添加mysql和mybatis 的maven依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2、在src/main/resources 目录下创建mybatis目录,并在下面创建mybatis-config.xml,同时创建一个mapper目录,用于存放sql映射文件
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>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
</configuration>
3、在application.properties中添加数据库连接信息 和 mybatis配置信息
#mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/boot_v2?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
#mybatis
#扫描指定路径下的实体,并用实体的简单名称作为别名
mybatis.type-aliases-package=com.ldy.bootv2.demo.entity
#自动扫描加载mybatis配置文件
mybatis.config-location=classpath:mybatis/mybatis-config.xml
#自动扫描加载Sql映射文件
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
#mapper目录下分多个模块时可以这样写
#mybatis.mapper-locations=classpath:mybatis/mapper/*/*.xml
4、创建数据库表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`age` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', '20', 'zs'), ('2', '21', 'ls');
5、编写数据库表对应实体类 :UserEntity.java
package com.ldy.bootv2.demo.entity;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel
public class UserEntity implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value="id,新建时不传,修改时传")
private Integer id;
@ApiModelProperty(value="名称")
private String userName;
@ApiModelProperty(value="年龄")
private Integer userAge;
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;
}
public Integer getUserAge() {
return userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
}
6、编写Dao层代码:UserMapper.java
package com.ldy.bootv2.demo.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.ldy.bootv2.demo.entity.UserEntity;
@Mapper
public interface UserMapper {
List<UserEntity> getAll();
UserEntity getOne(Integer id);
int insert(UserEntity user);
int update(UserEntity user);
int delete(Integer id);
}
7、编写Controller:UserController
package com.ldy.bootv2.demo.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ldy.bootv2.demo.entity.UserEntity;
import com.ldy.bootv2.demo.mapper.UserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@Api(tags = "用户信息管理接口-API")
@RestController
@RequestMapping("/user")
public class UserController {
private static Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
UserMapper userMapper;
@GetMapping("/findAll")
@ApiOperation("查询全部用户")
public List<UserEntity> findAll() {
logger.info("您调用了findAll接口");
return userMapper.getAll();
}
@GetMapping("/getOne/{id}")
@ApiOperation("根据ID查询用户")
public UserEntity getOne(@ApiParam(value="用户id",required=true) @PathVariable("id") Integer id) {
logger.info("您调用了getOne接口");
return userMapper.getOne(id);
}
@PutMapping("/saveOrUpdate")
@ApiOperation("新增或者修改用户")
public String saveOrUpdate(@ModelAttribute UserEntity entity) {
logger.info("您调用了saveOrUpdate接口");
try {
if(null == entity.getId()) {
userMapper.insert(entity);
}else {
userMapper.update(entity);
}
} catch (Exception e) {
logger.error("失败,原因:" + e.getMessage());
return "error";
}
return "success";
}
@DeleteMapping("/delete/{id}")
@ApiOperation("根据ID删除用户")
public String deleteById(@ApiParam(value="用户id",required=true) @PathVariable("id") Integer id) {
logger.info("您调用了delete接口");
try {
userMapper.delete(id);
} catch (Exception e) {
logger.error("失败,原因:" + e.getMessage());
return "error";
}
return "success";
}
}
8、运行项目,打开swagger页面,测试接口正常,swagger的集成请查看:https://blog.csdn.net/LDY1016/article/details/83415640
源码下载地址:https://pan.baidu.com/s/1Z771VDiuabDBJJV445xLeA#list/path=%2Fspring%20boot%202.x%20%E4%BB%A3%E7%A0%81
还没有评论,来说两句吧...