springboot_數據訪問之mybatis整合
阿新 • • 發佈:2019-05-03
close all dst from dao層 版本 template 編寫 text
一:引言:
大部分系統都涉及到數據訪問,數據庫包SQL(關系型數據庫)和NOSQL(非關系型數據庫),SQL包括:sqlserver,Oracle,Mysql;NOSQL包括:MongoDB和redis。
二:spring boot與jdbc整合
1.1 首先添加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
1.2 數據源配置
spring: datasource: url: jdbc:mysql://192.168.1.102:3306/jdbc username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver
測試類:測試:
@RunWith(SpringRunner.class) @SpringBootTest public class springbootjdbc { @Autowired DataSource dataSource; @Test public void contextLoads() throws SQLException { System.out.println("---------------"); System.out.println(dataSource.getClass()); Connection connection= dataSource.getConnection(); System.out.println("================="); System.out.println(connection); connection.close(); } }
控制臺輸出:
---------------
class com.zaxxer.hikari.HikariDataSource
2019-05-03 09:25:32.889 INFO 13768 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-05-03 09:25:33.500 INFO 13768 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
=================
[email protected] wrapping [email protected]
springboot默認的數據源就是:class com.zaxxer.hikari.HikariDataSource,數據源的相關配置都在DataSourceProperties裏面;
我們也可以自己默認數據源:spring.datasource.type可以自定義。
1.3 DataSourceInitializer
? 1)、runSchemaScripts();運行建表語句;
? 2)、runDataScripts();運行插入數據的sql語句;
默認只需要將文件命名為:
schema-*.sql、data-*.sql
默認規則:schema.sql,schema-all.sql;
可以使用
schema:
- classpath:department.sql
指定位置
1.4 操作數據庫
springboot自動配置了JdbcTemplate操作數據庫。
@Controller public class jdbc { @Autowired JdbcTemplate jdbcTemplate; @ResponseBody @RequestMapping("/h1") public Map<String, Object> selectAll() { List< Map<String, Object>> maps = jdbcTemplate.queryForList("select *from user "); System.out.println(maps.toString()); return maps.get(0); } }
訪問地址:http://localhost:8686/h1
控制臺打印:[{id=1, name=lisi, age=12}, {id=2, name=wangwu, age=13}]
二:整合Druid數據源
1.1 導入依賴(版本可選擇最新的)
<!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency>
1.2 .1配置文件:
spring:
datasource:
url: jdbc:mysql://192.168.1.102:3306/jdbc
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#數據源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置監控統計攔截的filters,去掉後監控界面sql無法統計,‘wall‘用於防火墻
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
1.2.2 編寫配置類 druidConfig 並以引入日誌依賴
@Configuration public class druidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druid() { return new DruidDataSource(); } }
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
在之前的測試類中:debug測試:
可以看到和我們之前在配置文件配置的一樣。
1.2.3 在配置類中 配置druid後臺監控;
@Configuration public class druidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druid() { return new DruidDataSource(); } // 配置Druid的監控 // 1、配置一個管理後臺的Servlet @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); Map<String,String> initParams = new HashMap<>(); initParams.put("loginUsername","admin"); initParams.put("loginPassword","123456"); initParams.put("allow",""); //默認就是允許所有訪問 initParams.put("deny","192.168.15.21"); bean.setInitParameters(initParams); return bean; } //2、配置一個web監控的filter @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); Map<String,String> initParams = new HashMap<>(); initParams.put("exclusions","*.js,*.css,/druid/*"); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean; } }
這樣就可以通過後臺監控數據源的訪問情況了。
輸入:
三:整合mybatis
1.1添加依賴
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-sta1rter</artifactId> <version>1.3.2</version> </dependency>
1.2.1 註解版
? 2)、給數據庫建表
? 3)、創建JavaBean
dao層:
@Mapper public interface userMapper { @Select("select *from user where id=#{id}") User selelctById(Integer id); @Delete("delete from user where id=#{id}") Integer delectById(Integer id); @Insert("insert into user(name,age) values(#{name},#{age}) ") User insertUser(User user); @Update("update user set name=#{name}where id=#{id}") Integer updateById(Integer id); }
測試userController:
@RestController public class UserController { @Autowired userMapper usermapper; @RequestMapping("/selectById") public User selectById(){ return usermapper.selelctById(2); } }
測試結果:
1.2.2 配置文件版
配置文件添加:
mybatis: mapper-locations: classpath:mybatis/mapper/*.xml 指定sql映射文件的位置
type-aliases-package: com.springboot.springboot.pojo 指定實體類所在的包
springboot_數據訪問之mybatis整合