本文讲解使用Spring-Data-Jpa操作数据库。

  JPA定义了一系列对象持久化的标准。

一、在项目中使用Spring-Data-Jpa

1. 配置文件application.properties中配置如下代码:

spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dbstudent
username: root
password: ccvdp
jpa:
hibernate:
ddl-auto: update
show-sql: true

注:spring.jpa.ddl-auto的值如下:

a.create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表                                数据丢失的一个重要原因
                          b.create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除
                          c.update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结                              构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才                             会
                          d.validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值
                          e.none:没有配置

2. pom.xml添加如下依赖:

<!-- JPA依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- mysql依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

3. 创建数据表实体类

package com.aston.reader.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id; @Entity
public class Student {
@Id
@GeneratedValue
private Integer id;
private String name;
private Integer age; public Student(){
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
}
}

启动项目,会自动创建数据表。

4. 创建Repository接口StudentRepository

package com.aston.reader.interfaces;

import com.aston.reader.model.Student;
import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface StudentRepository extends JpaRepository<Student, Integer>{
/**
* 扩展,按年龄查询
* @param age
* @return
*/
public List<Student> findByAge( Integer age);
}

5. 创建操作数据库类

package com.aston.reader.controller;

import com.aston.reader.interfaces.StudentRepository;
import com.aston.reader.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import java.util.List; @RestController
public class StudentController {
@Autowired
private StudentRepository studentRepository; /**
* 查询学生列表
* @return
*/
@GetMapping(value = "/students")
public List<Student> getStudentList(){
return studentRepository.findAll();
} /**
* 添加学生
* @param name
* @param age
* @return
*/
@PostMapping(value = "/addStudent")
public Student addStudent( @RequestParam("name") String name, @RequestParam("age") Integer age){
Student student = new Student(); student.setAge( age);
student.setName( name); return studentRepository.save( student);
} /**
* 根据ID查询学生
* @param id
* @return
*/
@GetMapping(value = "findStudent/{id}")
public Student findById(@PathVariable("id") Integer id){
return studentRepository.findOne(id);
} /**
* 根据ID更新student记录
* @param id
* @param name
* @param age
* @return
*/
@PutMapping(value = "/student/{id}")
public Student updateStudent(@PathVariable("id") Integer id, @RequestParam("name") String name, @RequestParam("age") Integer age){
Student student = new Student(); student.setId( id);
student.setName( name);
student.setAge( age); return studentRepository.save( student);
} /**
* 根据ID删除记录
* @param id
*/
@DeleteMapping(value = "student/{id}")
public void deleteStudent(@PathVariable("id") Integer id){
studentRepository.delete(id);
} /**
* 扩展,按年龄查询记录
* @param age
* @return
*/
@GetMapping(value = "/findByAge")
public List<Student > findByAge(@RequestParam("age") Integer age){
return studentRepository.findByAge( age);
}
}

二、注意

有一个扩展的操作。

三、事务管理

涉及数据库操作就必然会用到事务。事务指访问并可能更新数据库中各种数据项的一个程序执行单元(unit)。

Spring Boot的事务使用比较简单,只需在方法上使用注解 @Transactional。代码实例如下:

import javax.transaction.Transactional;

@Transactional
public void insertStudents(){
Student student1 = new Student();
student1.setName("zhangsan");
student1.setAge(17);
studentRepository.save(student1); Student student2 = new Student();
student2.setName("lisi");
//student2.setAge(111);
studentRepository.save(student2);
}

在操作数据库时要认真考虑事务的范围。只有查询的时候可以不需要加事务。

Spring Boot学习——数据库操作及事务管理的更多相关文章

  1. spring boot学习(6) SpringBoot 之事务管理

    两个操作要么同时成功,要么同时失败: 事务的一致性: 以前学ssh ssm都有事务管理service层通过applicationContext.xml配置,所有service方法都加上事务操作: 用来 ...

  2. spring boot中的声明式事务管理及编程式事务管理

    这几天在做一个功能,具体的情况是这样的: 项目中原有的几个功能模块中有数据上报的功能,现在需要在这几个功能模块的上报之后生成一条消息记录,然后入库,在写个接口供前台来拉取消息记录. 看到这个需求,首先 ...

  3. spring框架学习笔记7:事务管理及案例

    Spring提供了一套管理项目中的事务的机制 以前写过一篇简单的介绍事务的随笔:http://www.cnblogs.com/xuyiqing/p/8430214.html 还有一篇Hibernate ...

  4. 【Spring Boot学习之五】切面日志管理

    环境 eclipse 4.7 jdk 1.8 Spring Boot 1.5.2 一.log4j 常见方式:log4j.properties + org.apache.log4j.Logger比如:l ...

  5. Github点赞超多的Spring Boot学习教程+实战项目推荐!

    Github点赞接近 100k 的Spring Boot学习教程+实战项目推荐!   很明显的一个现象,除了一些老项目,现在 Java 后端项目基本都是基于 Spring Boot 进行开发,毕竟它这 ...

  6. Spring Boot学习笔记2——基本使用之最佳实践[z]

    前言 在上一篇文章Spring Boot 学习笔记1——初体验之3分钟启动你的Web应用已经对Spring Boot的基本体系与基本使用进行了学习,本文主要目的是更加进一步的来说明对于Spring B ...

  7. Spring Boot学习路线

    Spring Boot 学习路线,本文计划根据作者近几年的工作.学习经验,来分析和制定一个学习使用 Spring Boot技术的步骤路线图. SpringBoot是伴随着Spring4.0诞生的: S ...

  8. 15 个优秀开源的 Spring Boot 学习项目,一网打尽!

    Spring Boot 算是目前 Java 领域最火的技术栈了,松哥年初出版的 <Spring Boot + Vue 全栈开发实战>迄今为止已经加印了 8 次,Spring Boot 的受 ...

  9. 15 个优秀开源的 Spring Boot 学习项目

    Spring Boot 算是目前 Java 领域最火的技术栈了,松哥年初出版的 <Spring Boot + Vue 全栈开发实战>迄今为止已经加印了 8 次,Spring Boot 的受 ...

随机推荐

  1. h5中的video与audio

    ·首先带大家熟悉一下video标签的属性方法,根据属性方法做一个小demo, HTML5支持的视频格式: Ogg 带有Theora视频编码+Ogg文件 支持的浏览器:F.O MEPG4  带有H.26 ...

  2. 【Mysql】mysql中bigint、int、mediumint、smallint 和 tinyint的取值范围

    1.bigint 从 -2^63 (-9223372036854775808) 到 2^63-1 (9223372036854775807) 的整型数据(所有数字),无符号的范围是0到 1844674 ...

  3. 利用PHPExcel 实现excel数据的导入导出(源码实现)

    利用PHPExcel 实现excel数据的导入导出(源码实现) 在开发过程中,经常会遇到导入导出的需求,利用phpexcel类实现起来也是比较容易的,下面,我们一步一步实现 提前将phpexcel类下 ...

  4. hprose 1.0(rpc 框架) - 关于跨域和P3P的声明

    private function sendHeader($context) { if ($this->onSendHeader !== null) { $sendHeader = $this-& ...

  5. 想成长为一名年薪50万+的实战型架构师?必掌握这7大实战技能经验--阿里mike

    想成为一名架构师,但是架构师对应的技能,我应该掌握哪些啊?以及掌握的程度是什么样的?如何成为一名真正的实战性架构师? 我简要分为以下7点来谈谈,从技能的角度抛砖引玉,希望你对你架构师之路有一定的参考. ...

  6. 用描述符实现classmethod方法和staticmethod方法

    1. @classmethod class ClassMethod: def __init__(self, func): self.func = func def __get__(self, inst ...

  7. 51nod 1267二分+优化试验场

    最初,最开始的时候,万能的学姐曾经警告过我们,千万别用什么老狮子MAP,手撸map或者字典树...当时不甚理解...今天...这题直接卡掉了我的MAP,但是使用朴素方法进行二分...不加优化,,都不需 ...

  8. Kubespray部署Kubernetes 1.13.0(使用本地镜像仓库)

    1. 下载kubespray # git clone https://github.com/kubernetes-sigs/kubespray.git # cd kubespray # pip ins ...

  9. Failed to find provider info for com.tencent.mm.sdk.plugin.provider

    微信启动的时候可以调用,微信没启动,调用支付报这个错误. 我的问题是 微信发开着的jar包不是最新的,去官方网站下一个最新的就可以成功了.

  10. 9、JS对象 知识总结

    1.对象 <!DOCTYPE html> <html> <body> <script> <!-- 新建对象 --> person=new O ...