您的位置:首页 > 编程语言 > Java开发

springBoot整合JdbcTemplate

2017-09-11 13:57 746 查看
1.pom文件中加入

<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> 2.dao层
package com.aruisi.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.aruisi.dto.StudentEntity;
import com.aruisi.dto.StudentRowMapper;

@Repository
public class StudentRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
@Transactional(readOnly = true)
public List<StudentEntity> getStudentList(){
List<StudentEntity> studentList=jdbcTemplate.query("select id,name,sex,age from student",new StudentRowMapper());
System.out.println(studentList);
return studentList;
}
}3.service层
package com.aruisi.service;

import java.util.List;

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

import com.aruisi.dao.StudentRepository;
import com.aruisi.dto.StudentEntity;

@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
public List<StudentEntity> getStudentList(){
return studentRepository.getStudentList();
}
}4.controller层
package com.aruisi.controller;

import java.util.List;

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

import com.aruisi.dto.StudentEntity;
import com.aruisi.service.StudentService;

@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;

@RequestMapping("/list")
public List<StudentEntity> studentList() {
List<StudentEntity> studentList=studentService.getStudentList();
System.out.println(studentList);
return studentList;
}
}5.数据库配置文件application.properties
###### 设置tomcat访问端口号 ######
server.port=8085
###### 设置数据源 ######
spring.datasource.url=jdbc:mysql://localhost:3306/mytest?autoReconnect=true&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver代码下载地址
点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: