springboot: 集成jdbc

1.pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.lf</groupId>
  <artifactId>SpringBoot_Jdbc</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency> -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
  
</project>

 

2.service

package com.lf.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.lf.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    public List<Map<String, Object>> queryUser() {
        List<Map<String, Object>> queryForList = new ArrayList<Map<String,Object>>();
        try {
            queryForList = jdbcTemplate.queryForList("select * from t_user");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return queryForList;
    }

}

 

3.controller

package com.lf.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lf.service.UserService;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    
    @RequestMapping("queryUser")
    public String queryUser(){return userService.queryUser().toString();
    }
    
}

 

4.properties(目录为:/src/main/resources/application.properties,配置文件名称不能是其他的)

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=leifei
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

 

5.测试

 

posted @ 2018-01-24 18:26  拾柴小斯  阅读(1359)  评论(0编辑  收藏  举报