gyd_Alan
2018-11-26 14:51:30
SpringBoot连接数据库的方式
记一下Spring Boot 成功连接Mysql数据库的方法步骤!
一、新建Maven工程,在pom.xml引入SpringBoot的依赖包!
可以参照:http://www.cnblogs.com/liangblog/p/5207855.html
二、有两种方法与数据库建立连接:一种是集成JdbcTemplate,另一种用Mybatis自带插件
(1)、用JdbcTemplate
添加数据库依赖:
在resource文件夹下添加application.properties配置文件并输入数据库参数,如下:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.max-idle=10 spring.datasource.max-wait=10000 spring.datasource.min-idle=5 spring.datasource.initial-size=5 debug=true server.port=8011 server.session.timeout=10 server.tomcat.uri-encoding=UTF-8 # mybatis.config= classpath:mybatis-config.xml mybatis.mapper-locations=classpath:mappers/*Mapper.xml spring.profiles.active=@profiles.active@ # domain object's package mybatis.typeAliasesPackage=com.lgp.SpringBoot.bean # handler's package # mybatis.typeHandlersPackage= # check the mybatis configuration exists # mybatis.check-config-location= # mode of execution. Default is SIMPLE # mybatis.executorType=
新建Controller类测试数据库连接(DbController.java)
运行测试类, 输出数据库数据
(2)、集成Mybatis
添加mybatis依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> <!--添加JDBC依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--添加MySql依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
评论
最近浏览
fangen0005 LV25
2022年3月1日
卡拉kala LV1
2022年1月6日
焦老板的小跟班
2021年7月24日
暂无贡献等级
969226550
2021年7月1日
暂无贡献等级
liuyan1314 LV2
2021年6月15日
1028615763
2021年5月6日
暂无贡献等级
江辞123456 LV1
2020年12月24日
hugejihu9 LV1
2020年12月8日
1355862436 LV9
2020年11月6日
黄振宇
2020年10月14日
暂无贡献等级