本文直接将spring boot 与mybatis整合记录,接口为 RESTful风格,不懂什么是RESTful的请先问问度娘, 话不多说直接开始
一、新建Spring boot项目
推荐使用IntelliJ IDEA,IDEA的强大就不多说了,下面看图:
选择file-->new proect-->Spring Initializr,然后配置JDK和初始化的url地址,推荐使用默认,之后点击next
然后配置相关属性设置,各属性含义我就不解释了,都明白,点击next
在此界面可以看到有非常多的依赖,点击左侧的栏目在中间会显示出该栏目下包含的依赖;可以根据个人需求选择不同的依赖进行添加到项目中,本次示例选择的是:Web、JPA、JDBC、MyBatis;
在中间栏顶部可以选择Spring boot的版本,如下图:
选择好自己需要的依赖后点击 next
在此页面设置项目名称和存放位置,没什么好说的,点击 Finish 完成 项目新建,之后会下载各部分依赖 jar 包,稍等片刻即可创建完成。
二、编写
2.1所需要的完成POM文件如下
<?xml version="1.0" encoding="UTF-8"?>
<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.springboot_mybaties</groupId>
<artifactId>springboot_mybaties</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_mybaties</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.2,配置文件
配置文件存在于 resource 目录下,resource目录下还有static和templates文件夹,如下图所示:
static:主要用于存放一些css样式和js脚本文件
templates:存放html等一些模板类文件
application文件默认是properties格式,但是此格式缺乏层次性,而spring boot 配置文件也可以使用yml格式,这种格式配置起来很简洁,层次感很强;具体配置如下图:
spring:
datasource:
url: jdbc:mysql://localhost/model?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: sys
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
jpa:
database: MySQL
hibernate:
ddl-auto: update
naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
show-sql: true
open-in-view: true
server:
port: 8088
怎么样?看起来是不是很舒服?
2.3 编写代码
User.java
package com.springboot_mybatis.bean;
import javax.persistence.*;
/**
* @ClassName User
* @Description TODO
* @Author zhang
* @Date 2018-08-29 下午 1:40
* @Version 1.0
*/
@Entity//表明这个类作为实体类
@Table(name = "t_user_info")//制定实体类对应的表名
public class User {
private static final long serialVersionUID = -3039703447657705408L;
@Id//声明为主键
@GeneratedValue//自动递增
@Column(name = "id")//与@Table声明的表中列名对应
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private int age;
@Column(name = "country")
private String country;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", country='" + country + '\'' +
'}';
}
}
UserDao.java
package com.springboot_mybatis.mapper;
import com.springboot_mybatis.bean.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper//声明为Dao接口
public interface UserDao{
//如果使用 JPA注解方式指定过实体类和数据库映射之后这里就可以不使用@Resoults注解来映射返回值和实体类
@Select("select * from t_user_info where id=#{id}")
List<User> findById(Long id);
//此处sql语句中获取参数方式与XML中一致
@Insert("insert into t_user_info(name,age,country) values(#{name},#{age},#{country})")
void insertUser(User user);
}
UserService和UserServiceimpl类
package com.springboot_mybatis.service;
import com.springboot_mybatis.bean.User;
import java.util.List;
public interface UserService {
List<User> findById(Long id);
void insertUser(User user);
}
package com.springboot_mybatis.service.impl;
import com.springboot_mybatis.bean.User;
import com.springboot_mybatis.mapper.UserDao;
import com.springboot_mybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @ClassName UserServiceimpl
* @Description TODO
* @Author zhang
* @Date 2018-08-29 下午 1:59
* @Version 1.0
*/
@Service
public class UserServiceimpl implements UserService {
@Autowired//自动注入Dao
private UserDao userDao;
@Override
public List<User> findById(Long id) {
return userDao.findById(id);
}
@Override
public void insertUser(User user) {
userDao.insertUser(user);
}
}
UserController
package com.springboot_mybatis.controller;
import com.springboot_mybatis.bean.User;
import com.springboot_mybatis.service.UserService;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @ClassName UserController
* @Description TODO
* @Author zhang
* @Date 2018-08-29 下午 2:05
* @Version 1.0
*/
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public List<User> findById(@PathVariable("id") Long id) {
return userService.findById(id);
}
@PostMapping("/user")
public void addUser(@RequestParam("name") String name, @RequestParam("age") Integer age, @RequestParam("country") String country) {
User user = new User();
user.setAge(age);
user.setCountry(country);
user.setName(name);
userService.insertUser(user);
}
}
application类
package com.springboot_mybatis;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("com.springboot_mybatis")//配置扫描包,防止出现找不到类的情况出现
@MapperScan("com.springboot_mybatis.mapper")//扫描Dao包
public class SpringbootMybatiesApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatiesApplication.class, args);
}
}
好了,到这里基本已经编写完成了,开始测试吧!!!
三、测试
我使用的是Postman测试工具来测试接口,至于详细使用说明请自行百度
在地址栏中输入地址,之后填写相关参数,点击蓝色Send按钮,返回值为空
没有报错,既是执行成功,查看数据库
添加成功!!
接下来测试查询接口:
成功!!
至此项目基本完成。