整合框架一定要细心细心加细心,很多问题都是因为单词写错或者漏写配置造成的。
1.准备
配置idea相关maven环境
准备数据库
用mybatis的逆向工程加载出相关文件。
第一步:创建相关项目:new-project-spring-initialler,选择web、mysql、jdbc、mybatis
第二步:
在pom.xml加入druid依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
第三步编写druid配置文件
在resources下新建application.yml(这个文件用来写druid的相关配置)
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/hms?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
type: com.alibaba.druid.pool.DruidDataSource
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
connect-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
注意:每一个词都不要出差错:不要把mapper-locations写成mapper-localtion不然扫描不到相关文件还有url后的设置。
第三步新建配置类配置druid
```
package com.yzx.demo.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
}
```
第四步:将mapper、bean、xml引入
第五步:编写mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>
</configuration>
在之前的application.yml文件中会扫描相关配置
第六步:使用
package com.yzx.demo.controller;
import com.yzx.demo.bean.Room;
import com.yzx.demo.bean.User;
import com.yzx.demo.mapper.RoomMapper;
import com.yzx.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@ResponseBody
public class Mapping {
@Autowired
private RoomMapper roomMappers;
@RequestMapping("/select")
public Room getusers() {
return roomMappers.selectByPrimaryKey(1);
}
}
运行效果:
网友评论