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 父类
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
增加依赖项
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.27</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<!--<version>5.0.0</version> -->
<version>4.1.6</version>
</dependency>
<!-- 打war包用 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<packaging>war</packaging>
<!-- -->
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<!-- 打war包用 -->
<finalName>demo</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- 打war包用,maven打包的时候告诉maven不需要web.xml,否刚会报找不到web.xml错误 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<!-- -->
</plugins>
</build>
增加主要的入口类和配置
文件的位置
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
我们先运行下看看效果吧
在Application.java 类中右键运行
启动成功了
使用IDE工具测试下吧
Tools > Test Restful Web Service
运行
或者在浏览器地址栏访问
http://localhost:8080/demo
下面整合MyBatis
首先补充上完整的application.properties 配置内容包含了数据库的配置
记得修改你自己的数据库账号和密码
server.port=8080server.context-path=/demo
druid.driver=com.mysql.jdbc.Driver
druid.url=jdbc:mysql://localhost:3306/mysqldruid.username=root
druid.password=123456druid.init-size=1druid.min-idel=1druid.max-active=5druid.login.timeout.seconds=30druid.query.timeout.seconds=30
resources/mybatis-config.xml
注意了!注意了! 每次增加xml配置记得要在这里增加mapper配置
<?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>
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="true"/>
<setting name="useGeneratedKeys" value="true"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="600"/>
<setting name="callSettersOnNulls" value="true"/>
</settings>
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="sqlserver"/>
</plugin>
</plugins>
<mappers>
<mapper resource="mappers/HelpCategoryMapper.xml"/>
</mappers></configuration>
这里我们写一个简单的查询语句
resources/mappers/HelpCategoryMapper.xml
<?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.yundian.mapper.HelpCategoryMapper">
<resultMap id="BaseResultMap" type="com.yundian.entity.HelpCategory">
<id column="help_category_id" jdbcType="SMALLINT" property="helpCategoryId" />
<result column="name" jdbcType="CHAR" property="name" />
<result column="parent_category_id" jdbcType="SMALLINT" property="parentCategoryId" />
<result column="url" jdbcType="CHAR" property="url" />
</resultMap>
<select id="selectList" resultMap="BaseResultMap">
select help_category_id, name, parent_category_id, url from help_category </select></mapper>
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<HelpCategory> selectList();
}
HelpCategoryService.java
package com.yundian.service;
import com.yundian.entity.HelpCategory;
import java.util.List;
public interface HelpCategoryService {
List<HelpCategory> 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<HelpCategory> 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<HelpCategory> list = helpCategoryService.selectList(); return new Result<>(Code.SUCCESS, list);
}
}
其他的两个公共类
Result.java
package com.yundian.common;
import com.yundian.enums.Code;
public class Result<T> {
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;
}
}
到这里所有的类都编写完了,好了见证奇迹的时候到了
你的运行结果对了吗?
更多精彩内容请关注“IT实战联盟”公众号哦~~~
注意:本文归作者所有,未经作者允许,不得转载