springboot连接mysql_Spring Boot高级教程之Spring Boot连接MySql数据库

Spring Boot可以大大简化持久化任务,几乎不需要写SQL语句,在之前章节“Spring Boot 构建框架”中我们新建了一个Spring Boot应用程序,本章在原有的工程中与数据库建立连接。

Spring Boot有两种方法与数据库建立连接,一种是使用JdbcTemplate,另一种集成Mybatis,下面分别为大家介绍一下如何集成和使用这两种方式。

1. 使用JdbcTemplate

mysql

mysql-connector-java

org.springframework.boot

spring-boot-starter-jdbc

在resource文件夹下添加application.properties配置文件并输入数据库参数,内容如下:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test

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=1000

spring.datasource.min-idle=5

spring.datasource.initial-size=5

server.port=8012

server.session.timeout=10

server.tomcat.uri-encoding=UTF-8

新建Controller类测试数据库连接,实例如下:

package com.example.demo;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

@RequestMapping("/mydb")

public class DBController {

@Autowired

private JdbcTemplate jdbcTemplate;

@RequestMapping("/getUsers")

public List> getDbType(){

String sql = "select * from appuser";

List> list = jdbcTemplate.queryForList(sql);

for (Map map : list) {

Set> entries = map.entrySet( );

if(entries != null) {

Iterator> iterator = entries.iterator( );

while(i

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值