一、介绍

  SpringBoot框架为使用SQL数据库提供了广泛的支持,从使用JdbcTemplate的直接JDBC访问到完整的“对象关系映射”技术(如Hibernate)。Spring-data-jpa提供了额外的功能级别:直接从接口创建存储库实现,并使用约定方法名生成查询。

  建表:

CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `user` VALUES ('3', 'andy', '6', 'month');
INSERT INTO `user` VALUES ('4', 'andy', '7', 'month');
INSERT INTO `user` VALUES ('5', 'andy', '8', 'month');
INSERT INTO `user` VALUES ('6', 'jack', '3', 'aaa');
CREATE TABLE `student` (
`id` int(11) NOT NULL,
`age` int(11) NOT NULL,
`grade` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `student` VALUES ('1', '2', '3', 'jack');
INSERT INTO `student` VALUES ('2', '4', '2', 'andy');

二、JdbcTemplate

  在需要使用持久层的类中直接注入JdbcTemplate,在基本的SpringBoot配置(SpringBoot-HelloWorld)下增加配置数据库连接驱动器:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>

  配置jdbc的依赖库:

<!-- jdbcTemplate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

  在application.properties默认属性文件中增加数据库连接信息:

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

  创建实体类user:

package com.cn.entity;

import java.io.Serializable;

/**
* @program: spring-boot-example
* @description: 用户类
* @author:
* @create: 2018-05-02 09:59
**/
public class User implements Serializable{ private int id;
private String name;
private int age;
private String address; @Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
}
}

User.java

  创建UserService接口,UserServiceImpl(内有User映射内部类)服务实现类:

package com.cn.service;

import com.cn.entity.User;
import java.util.List; /**
* @program: spring-boot-example
* @description:
* @author:
* @create: 2018-05-02 10:02
**/ public interface UserService { User getUserById(int id); List<User> getUsers(); int deleteUserById(int id); int updateUserById(User user); int insertUser(User user); }

UserService.java

package com.cn.service;

import com.cn.entity.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service; /**
* @program: spring-boot-example
* @description:
* @author:
* @create: 2018-05-02 10:07
**/ @Service
public class UserServiceImpl implements UserService{ @Autowired
private JdbcTemplate jdbcTemplate; @Override
public User getUserById(int id) {
User user = jdbcTemplate.queryForObject("select * from user where id=?", new Object[]{id},new UserRowMapper());
return user;
} @Override
public List<User> getUsers() {
return jdbcTemplate.query("select * from user",new UserRowMapper());
} @Override
public int deleteUserById(int id) {
return jdbcTemplate.update("delete from user where id=?", new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement preparedStatement) throws SQLException {
preparedStatement.setInt(1,id);
}
});
} @Override
public int updateUserById(User user) {
return jdbcTemplate.update("update user SET name=?,age=?,address=? where id=?", new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement preparedStatement) throws SQLException {
preparedStatement.setString(1,user.getName());
preparedStatement.setInt(2,user.getAge());
preparedStatement.setString(3,user.getAddress());
preparedStatement.setInt(4,user.getId());
}
});
} @Override
public int insertUser(User user) {
String sql = "insert into user(name,age,address) VALUES (?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(sql,new String[]{"id"});
preparedStatement.setString(1,user.getName());
preparedStatement.setInt(2,user.getAge());
preparedStatement.setString(3,user.getAddress());
return preparedStatement;
}
},keyHolder);
return Integer.parseInt(keyHolder.getKey().toString());
}
}
class UserRowMapper implements RowMapper<User> { @Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User user=new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setAge(resultSet.getInt("age"));
user.setAddress(resultSet.getString("address"));
return user;
} }

UserServiceImpl.java

  创建UserController:

package com.cn.controller;

import com.cn.entity.User;
import com.cn.service.UserService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; /**
* @program: spring-boot-example
* @description:
* @author:
* @create: 2018-05-02 09:58
**/ @RestController
public class UserController { @Autowired
private UserService userService; @RequestMapping(value = "getUserById/{id}",method = RequestMethod.GET)
public User getUserById(@PathVariable int id) {
return userService.getUserById(id);
} @RequestMapping("getUsers")
public List<User> getUsers() {
return userService.getUsers();
} @RequestMapping(value = "updateUserById",method = RequestMethod.POST)
public int updateUserByUd(User user) {
return userService.updateUserById(user);
} @RequestMapping(value = "insertUser",method = RequestMethod.POST)
public int insertUser(User user) {
return userService.insertUser(user);
} @RequestMapping(value = "deleteUserById/{id}",method = RequestMethod.DELETE)
public int deleteUserById(@PathVariable int id) {
return userService.deleteUserById(id);
}
}

UserController.java

  使用Postman工具测试(有两种:浏览器插件版,安装版,我用的是安装版),这里简单列举几个测试结果:

  

  

  

三、JpaRepository

  Java Persistence API是一种标准技术,可以将对象“映射”到关系数据库。spring-boot-starter-data-jpa POM提供了一种快速入门的方法。它提供了以下关键依赖项:

  • Hibernate: One of the most popular JPA implementations.
  • Spring Data JPA: Makes it easy to implement JPA-based repositories.
  • Spring ORMs: Core ORM support from the Spring Framework.

  使用方法:创建持久层实现接口,并用接口实现JpaRepository<%Bean%,%PrimaryKey%>(Bean为实体类,PrimaryKey为实体类的主键,在JpaRepository中已经有部分接口方法,视情况自加);

  增加pom库的依赖:

<!-- spring-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

  创建实体类Student(注意要声明实体类的注解,@Entity、@Id):

package com.cn.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id; /**
* @program: spring-boot-example
* @description: 学生实体类
* @author:
* @create: 2018-05-02 10:47
**/ @Entity
public class Student { @Id
@GeneratedValue
private int id; private String name; private int age; private int grade; @Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", grade=" + grade +
'}';
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public int getGrade() {
return grade;
} public void setGrade(int grade) {
this.grade = grade;
}
}

Student.java

  创建StudentService接口,StudentServiceImpl实现类:

package com.cn.service;

import com.cn.entity.Student;

/**
* @program: spring-boot-example
* @description:
* @author:
* @create: 2018-05-02 11:12
**/
public interface StudentService { Student findByName(String name); Student findByNameAndAge(String name, Integer age); Student findUser(String name); }

StudentService.java

package com.cn.service;

import com.cn.dao.StudentDao;
import com.cn.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; /**
* @program: spring-boot-example
* @description:
* @author:
* @create: 2018-05-02 11:13
**/
@Service
public class StudentServiceImpl implements StudentService{ @Autowired
private StudentDao studentDao; @Override
public Student findByName(String name) {
return studentDao.findByName(name);
} @Override
public Student findByNameAndAge(String name, Integer age) {
return studentDao.findByNameAndAge(name,age);
} @Override
public Student findUser(String name) {
return studentDao.findUser(name);
}
}

StudentServiceImpl.java

  创建StudentController:

package com.cn.controller;

import com.cn.entity.Student;
import com.cn.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; /**
* @program: spring-boot-example
* @description:
* @author:
* @create: 2018-05-02 11:15
**/
@RestController
public class StudentController { @Autowired
private StudentService studentService; @RequestMapping("findByName/{name}")
public Student findByName(@PathVariable String name) {
return studentService.findByName(name);
} @RequestMapping("findByNameAndAge")
public Student findByNameAndAge(@RequestParam("name") String name,@RequestParam("age") Integer age) {
return studentService.findByNameAndAge(name,age);
} @RequestMapping("findUser/{name}")
public Student findUser(@PathVariable String name) {
return studentService.findUser(name);
}
}

StudentController.java

  同样适用Postman测试,结果如下:

  

  

完整示例:https://gitee.com/lfalex/spring-boot-example

参考官方文档:https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-documentation

(三)SpringBoot基础篇- 持久层,jdbcTemplate和JpaRespository的更多相关文章

  1. (三)SpringBoot2.0基础篇- 持久层,jdbcTemplate和JpaRespository

    一.介绍 SpringBoot框架为使用SQL数据库提供了广泛的支持,从使用JdbcTemplate的直接JDBC访问到完整的“对象关系映射”技术(如Hibernate).Spring-data-jp ...

  2. (二)SpringBoot基础篇- 静态资源的访问及Thymeleaf模板引擎的使用

    一.描述 在应用系统开发的过程中,不可避免的需要使用静态资源(浏览器看的懂,他可以有变量,例:HTML页面,css样式文件,文本,属性文件,图片等): 并且SpringBoot内置了Thymeleaf ...

  3. 视频作品《springboot基础篇》上线了

    1.场景描述 第一个视频作品出炉了,<springboot基础篇>上线了,有需要的朋友可以直接点击链接观看.(如需购买,请通过本文链接购买) 2. 课程内容 课程地址:https://ed ...

  4. Python(三)基础篇之「模块&面向对象编程」

    [笔记]Python(三)基础篇之「模块&面向对象编程」 2016-12-07 ZOE    编程之魅  Python Notes: ★ 如果你是第一次阅读,推荐先浏览:[重要公告]文章更新. ...

  5. SpringBoot基础篇-SpringBoot快速入门

    SpringBoot基础 学习目标: 能够理解Spring的优缺点 能够理解SpringBoot的特点 能够理解SpringBoot的核心功能 能够搭建SpringBoot的环境 能够完成applic ...

  6. (一)SpringBoot基础篇- 介绍及HelloWorld初体验

    1.SpringBoot介绍: 根据官方SpringBoot文档描述,BUILD ANYTHING WITH SPRING BOOT (用SPRING BOOT构建任何东西,很牛X呀!),下面是官方文 ...

  7. Springboot基础篇

    Springboot可以说是当前最火的java框架了,非常适合于"微服务"思路的开发,大幅缩短软件开发周期. 概念 过去Spring充满了配置bean的xml文件,随着spring ...

  8. SpringBoot基础篇AOP之基本使用姿势小结

    一般来讲,谈到Spring的特性,绕不过去的就是DI(依赖注入)和AOP(切面),在将bean的系列中,说了DI的多种使用姿势:接下来看一下AOP的玩法 <!-- more --> I. ...

  9. 学习笔记三:基础篇Linux基础

    Linux基础 直接选择排序>快速排序>基数排序>归并排序 >堆排序>Shell排序>冒泡排序=冒泡排序2 =直接插入排序 一.Linux磁盘分区表示 Linux中 ...

随机推荐

  1. pig读取部分列 (全部列中的少部分列)

    pig流式数据,load数据时,不能读入任意列. 但是,可以从头读,只能连续几列.就是前几列.比如10列数据,可以只读前3列.但不能读第3列: 如:数据testdata [wizad@sr104 lm ...

  2. Leetcode_21_Merge Two Sorted Lists

    ->4->4,return 1->2->3->4->5->6. 思路: (1)题意为将两个有序链表合成一个有序链表. (2)首先,分别对链表头结点判空,如果都 ...

  3. (NO.00001)iOS游戏SpeedBoy Lite成形记(二十)

    下面修改最为关键的matchRun方法里的代码: CCActionCallBlock *blk = [CCActionCallBlock actionWithBlock:^{ _finishedCou ...

  4. 学习pthreads,多线程的创建和终止

    在多CPU多线程的编程中,通过作者的学习发现,pthreads的运用越来越广泛,它是线程的POSIX标准,定义了创建和操作线程的一整套API.环境的配置见上一篇博文,配置好环境后只需要添加#inclu ...

  5. Binder和SurfaceFlinger以及SystemServer介绍-android学习之旅(79)

    由于binder机制的存在,使得进程A可以访问进程B中的对象. Android系统Binder机制中的四个组件Client.Server.Service Manager和Binder驱动程序: 1. ...

  6. Gradle 1.12用户指南翻译——第三十一章. FindBugs 插件

    其他章节的翻译请参见: http://blog.csdn.net/column/details/gradle-translation.html 翻译项目请关注Github上的地址: https://g ...

  7. 【Qt编程】基于QWT的曲线绘制及图例显示操作

    在<QWT在QtCreator中的安装与使用>一文中,我们完成了QWT的安装,这篇文章我们讲讲基础曲线的绘制功能. 首先,我们新建一个Qt应用程序,然后一路默认即可.这时,你会发现总共有: ...

  8. Web应用程序设计十个建议

    原文链接:  Top 10 Design Tips for Web Apps 原文日期: 2014年04月02日 翻译日期: 2014年04月11日 翻译人员: 铁锚 现代web应用通常在互联网上通过 ...

  9. 【Linux 操作系统】阿里云服务器 操作实战 部署C语言开发环境(vim配置,gcc) 部署J2EE网站(jdk,tomcat)

    . 作者 :万境绝尘  转载请注明出处 : http://blog.csdn.net/shulianghan/article/details/18964835 . 博客总结 : 设置SecureCRT ...

  10. 分布式版本库——Windows下Git的环境部署以及在GitHub上开源自己的项目

    分布式版本库--Windows下Git的环境部署以及在GitHub上开源自己的项目 这几天着实忙的焦头烂额,可惜不是搞技术,今天周日,难得闲下来,写篇大家都想学习的Git教程,其实廖雪峰老师的网站已经 ...