Spring的追求一定是简单点简单点,让java的开发变得更加简单、容易。Spring boot就是朝着这一追求更近了一步的天使,一个在Spring基础上的一整套实现。
期初,对Spring boot没有太多的好感,觉得它只不过是把java企业级应用必须用的servlet容器给干掉了而已。
进一步接触,才有所感悟,原来Spring boot是这么强大的一个东西。像boot这个名字和它的图标一样,就像是一台电脑的启动按钮,当你start之后,所有你需要的东西都准别好了。你需要做的,就是尽情享受现代科技的美妙。
下面就跟着我去搭建一个Spring Boot整合MyBatis的例子吧
默认这些东西都是需要有的: Jdk1.6+,Maven,MySql数据库
我们先看下已经完成的项目结构图
最终运行结果
下面开始一步一步的编写代码了
增加Spring boot的maven 依赖
继承spring boot 父类
org.springframework.boot
spring-boot-starter-parent
1.5.1.RELEASE
增加依赖项
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-jpa
org.apache.tomcat.embed
tomcat-embed-jasper
org.mybatis
mybatis
3.4.2
org.mybatis
mybatis-spring
1.3.1
mysql
mysql-connector-java
com.alibaba
druid
1.0.27
com.github.pagehelper
pagehelper
4.1.6
org.springframework.boot
spring-boot-starter-tomcat
provided
war
1.8
demo
org.springframework.boot
spring-boot-maven-plugin
org.apache.maven.plugins
maven-war-plugin
2.1.1
false
增加主要的入口类和配置
Application.java
package com.yundian;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class Application {
@RequestMapping("/")
public String index() {
return "Hello Spring Boot";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
application.properties
server.port=8080
server.context-path=/demo
我们先运行下看看效果吧
使用IDE工具测试下吧
或者在浏览器地址栏访问
http://localhost:8080/demo
下面整合MyBatis
首先补充上完整的application.properties 配置内容包含了数据库的配置
记得修改你自己的数据库账号和密码
server.port=8080
server.context-path=/demo
druid.driver=com.mysql.jdbc.Driver
druid.url=jdbc:mysql://localhost:3306/mysql
druid.username=root
druid.password=123456
druid.init-size=1
druid.min-idel=1
druid.max-active=5
druid.login.timeout.seconds=30
druid.query.timeout.seconds=30
resources/mybatis-config.xml
注意了!注意了! 每次增加xml配置记得要在这里增加mapper配置
这里我们写一个简单的查询语句
resources/mappers/HelpCategoryMapper.xml
com.yundian.configuration.DatasourceConfig.java
package com.yundian.configuration;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.yundian.mapper")
public class DatasourceConfig {
private static Logger log = LoggerFactory.getLogger(DatasourceConfig.class);
@Value("${druid.driver}")
private String driverClassName;
@Value("${druid.url}")
private String url;
@Value("${druid.username}")
private String username;
@Value("${druid.password}")
private String password;
@Value("${druid.init-size}")
private int initSize;
@Value("${druid.min-idel}")
private int minIdel;
@Value("${druid.max-active}")
private int maxActive;
@Value("${druid.login.timeout.seconds}")
private int loginTimeoutSeconds;
@Value("${druid.query.timeout.seconds}")
private int queryTimeoutSeconds;
@Bean
public DataSource dataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driverClassName);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
ds.setInitialSize(initSize);
ds.setMinIdle(minIdel);
ds.setMaxActive(maxActive);
ds.setLoginTimeout(loginTimeoutSeconds);
ds.setQueryTimeout(queryTimeoutSeconds);
return ds;
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
final SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource());
sqlSessionFactory.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
sqlSessionFactory.setFailFast(true);
return sqlSessionFactory.getObject();
}
public DataSourceTransactionManager dataSourceTransactionManager() {
log.debug("> transactionManager");
return new DataSourceTransactionManager(dataSource());
}
}
下面写一个实体类
这里我们用到了mysql数据库的系统表来做测试
HelpCategory.java
package com.yundian.entity;
public class HelpCategory {
private Short helpCategoryId;
private String name;
private Short parentCategoryId;
private String url;
// getter settter 方法省略了
}
HelpCategoryMapper.java
package com.yundian.mapper;
import com.yundian.entity.HelpCategory;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface HelpCategoryMapper {
List selectList();
}
HelpCategoryService.java
package com.yundian.service;
import com.yundian.entity.HelpCategory;
import java.util.List;
public interface HelpCategoryService {
List selectList();
}
HelpCategoryServiceImpl.java
package com.yundian.service.impl;
import com.yundian.entity.HelpCategory;
import com.yundian.mapper.HelpCategoryMapper;
import com.yundian.service.HelpCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class HelpCategoryServiceImpl implements HelpCategoryService {
@Autowired
private HelpCategoryMapper helpCategoryMapper;
@Override
public List selectList() {
return helpCategoryMapper.selectList();
}
}
HelpCategoryController.java
package com.yundian.controller;
import com.yundian.common.Result;
import com.yundian.entity.HelpCategory;
import com.yundian.enums.Code;
import com.yundian.service.HelpCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("help")
public class HelpCategoryController {
@Autowired
private HelpCategoryService helpCategoryService;
@RequestMapping(value = "category", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public Result category() {
List list = helpCategoryService.selectList();
return new Result<>(Code.SUCCESS, list);
}
}
其他的两个公共类
Result.java
package com.yundian.common;
import com.yundian.enums.Code;
public class Result {
private int code;
private String message;
private T result;
public Result(Code code, T result) {
this.code = code.getCode();
this.message = code.getDesc();
this.result = result;
}
// 省略了get set方法
}
Code.java
package com.yundian.enums;
public enum Code {
SUCCESS(100, "SUCCESS"), FAIL(101, "FAILED"), unknown(-1, "未知");
private int code;
private String desc;
Code(int code, String desc) {
this.code = code;
this.desc = desc;
}
public int getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
到这里所有的类都编写完了,好了见证奇迹的时候到了
你的运行结果对了吗?
更多精彩内容
架构实战篇(一):Spring Boot 整合MyBatis
架构实战篇(二):Spring Boot 整合Swagger2
架构实战篇(三):Spring Boot 整合MyBatis(二)
架构实战篇(四):Spring Boot 整合 Thymeleaf
架构实战篇(五):Spring Boot 表单验证和异常处理
架构实战篇(六):Spring Boot RestTemplate的使用
关注我们
如果需要源码可以关注“IT实战联盟”公众号并留言(源码名称+邮箱),小萌看到后会联系作者发送到邮箱,也可以加入交流群和作者互撩哦~~~!
IT实战联盟是集产品、UI设计、前后端、架构、大数据和AI人工智能等为一体的实战交流服务平台!联盟嘉宾都为各互联网公司项目的核心成员,联盟主旨是“让实战更简单”,欢迎来撩~~~