最近在用Springboot,记录下简单配置过程:
一、环境准备:
1、Java版本:1.8.0_151
2、Maven:3.3.9
3、开发工具:idea
4、数据库:Mysql
二、配置过过程:
1、新建springboot项目,可以通过 idea自动创建springboot项目或者通过网站:
SpringBoot Start
2、如果使用idea在新建过程中没有选择需要加载的控件,需要手动往pom里加入:mysql、mybatis、druid:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
3、修改application.yml文件(如果没有可以新建,如果是 application.properties文件也可以,同理),加入如下配置:
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
tomcat:
initial-size: 1
max-wait: 20
min-idle: 3
max-age: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: select 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
# http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
mybatis:
configuration:
map-underscore-to-camel-case: true
default-fetch-size: 100
default-statement-timeout: 3000
type-aliases-package: com.example.model
mapper-locations: classpath:com/example/mapper/*.xml
mybati相关参考地址:
mybatis-spring-boot-autoconfigure
4、新建一张表user(id,name),测试数据
5、新建dao和对应的xml文件:
@Mapper
public interface UserDao {
public User getById(@Param("id") int id);
}
<?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.bluefish.seckill.dao.UserDao">
<select id="getById" resultType="com.bluefish.seckill.model.User">
SELECT `id`, `name` from `user` WHERE `id`=#{id}
</select>
</mapper>
6、新建service类:
@Service("userService")
public class UserService {
@Autowired
private UserDao userDao;
public User getUserbyId(int id){
return userDao.getById(id);
}
}