您的位置:首页 > 编程语言 > Java开发

Spring Boot、Mybatis框架整合开发Java RESTful Web Service

2016-02-06 22:47 981 查看

Spring Boot、Mybatis 框架整合开发Java Web Restful Service

框架介绍

非常优秀的框架。。来自官网原文,想了解它们的魅力,点击标题直接去官网。。。

Spring Boot

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”. We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.

MyBatis

MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.

参考资料

Spring Boot 官方参考指南

Spring Boot 中文参考指南

Mybatis 官方中文文档

mybatis-spring-boot GitHub主页

项目创建

项目搭建环境一览

OS: Mac OS X 10.11

IDE: IDEA 15

构建工具: Maven 3

JDK version: 1.8

Database: MySQL

Spring Boot 项目创建



下一步(Next)



下一步(Next)



注意: 本项目勾选了3个依赖:web、jdbc、mysql,后期可根据需求增加依赖。

下一步(Next),填写项目名称,完成(Finish)

等待项目创建完成。创建完成后,如下图:



项目pom文件相关依赖可以参考官方文档理解。光速直达>>> Starter POMs

添加 MyBatis 依赖

添加mybatis-spring-boot依赖(Mybatis官方针对Spring Boot出的整合框架包,其本身依赖mybatis以及mybatis-spring,无需添加这两个依赖,Maven自动管理)



完善项目结构

根据需求,完善项目包结构,增加以下包:

1. controller 控制层(或命名为web)

2. service 服务层

3. dao 数据访问层(或命名为mapper, Mybatis的数据库操作接口层)

4. entity 实体类(或命名为model、domain)

5. util 工具类

SpringBootDemoApplication类需要放于basePackage下,这里与@SpringBootApplication 注解有关,是Spring Boot的配置约定。 光速直达>>> Structuring your code



创建数据库、数据表、实体类等

Mac OS X安装 MySQL、Navicat,请参考

创建数据库、数据表

d069

使用IDEA 提供的数据库工具连接MySQL,并进行数据库操作



在Data Source中选择MySQL,填写数据库连接信息,成功连接MySQL数据库后,创建测试使用的数据库spring_boot_mybatis。

创建数据表(用户表)

CREATE TABLE spring_boot_mybatis.user
(
id INT NOT NULL  PRIMARY KEY  AUTO_INCREMENT,
username VARCHAR(20) NOT NULL,
phone CHAR(11)  NOT NULL
);


添加测试数据。

使用Navicat连接MySQL,并进行操作数据库。

实体类

UserEntity
注释属性说明等。

/**
* 用户实体类
**/
public class UserEntity {
// 数据表主键
private int id;
// 用户名
private String username;
// 手机号码
private String phone;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}
}


数据层

UserDAO
MyBatis CURD接口类(使用注解方式)

@Repository
public interface UserDAO {

// 插入一行新数据
@Insert("INSERT INTO user(username,phone) VALUES(#{userEntity.username},#{userEntity.phone})")
@Options(useGeneratedKeys = true, keyProperty = "userEntity.id")  // 将自动生成的主键重新设置到实体中,便于业务逻辑处理
void insertUser(@Param("userEntity") UserEntity userEntity);

// 根据id查询用户
@Select("SELECT * FROM user WHERE id = #{id}")
@ResultType(UserEntity.class)
UserEntity findUserById(@Param("id") int id);
}


服务层

UserService
接口类,定义接口方法

/**
* UserService 接口类
**/
public interface UserService {
// 创建新用户
boolean createUser(UserEntity userEntity);
// 根据主键id查找用户
UserEntity findUserById(int id);

// ......
}


UserServiceImpl
实现类 ,业务逻辑处理,并返回结果。

@Service("userService") // 命名bean别名
public class UserServiceImpl implements UserService {

private final UserDAO userDAO;

// 依赖注入
@Autowired
public UserServiceImpl(UserDAO userDAO) {
this.userDAO = userDAO;
}

/**
*  创建新用户
* @param userEntity
* @return
*/
@Override
public boolean createUser(UserEntity userEntity) {
userDAO.insertUser(userEntity);
if (userEntity.getId() > 0) {
return true;
}
return false;
}

/**
*  根据id查询用户
* @param id
* @return
*/
@Override
public UserEntity findUserById(int id) {
return userDAO.findUserById(id);
}
// .......
}


控制层

UserController
处理 Request,并返回ResponseEntity。

@RestController
@RequestMapping("/users")
public class UserController {

@Autowired
private UserService userService;

/**
* 根据id查询用户
* @param id
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
public HttpEntity getUserById(@PathVariable("id") Integer id) {
UserEntity userEntity = userService.findUserById(id);

return new ResponseEntity<>(userEntity, HttpStatus.OK);
}

/**
* 创建用户
* @param userEntity
* @return
*/
@RequestMapping(method = RequestMethod.POST)
public HttpEntity createUser(@RequestBody UserEntity userEntity) {
boolean created = userService.createUser(userEntity);
if (!created) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity(HttpStatus.CREATED);
}
}


相关配置

注解

添加
@MapperScan
注解,Mybatis Mapper接口类 所在的包名。或其他注解,例如事务管理等。

@SpringBootApplication
@MapperScan(basePackages = "com.example.dao")
public class SpringBootDemoApplication {

public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}


配置文件

application.properties


# DataSource
spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot_mybatis
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=RXXW4MH8

# MyBatis
# mybatis.type-aliases-package=com.example.entity # 接口CURD方法中已经使用注解了结果数据的类类型,可以不配置此项

# Logging
logging.level.com.example.dao = DEBUG

# Jackson

# 等等配置


其他(待续)

事务管理

SSL

Log4j 2

MongoDB

JPA

OAuth2

Actuator

Developer tools

总结

到此,整合流程完毕,但还是有很多Spring Boot的特性没有用上,以后有时间再补上。^_^

如有错误,请不吝赐教哈。感谢!!

如有问题或技术交流,请联系: codingadai@126.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: