Spring Boot学习——数据库操作及事务管理
本文讲解使用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学习——数据库操作及事务管理的更多相关文章
- spring boot学习(6) SpringBoot 之事务管理
两个操作要么同时成功,要么同时失败: 事务的一致性: 以前学ssh ssm都有事务管理service层通过applicationContext.xml配置,所有service方法都加上事务操作: 用来 ...
- spring boot中的声明式事务管理及编程式事务管理
这几天在做一个功能,具体的情况是这样的: 项目中原有的几个功能模块中有数据上报的功能,现在需要在这几个功能模块的上报之后生成一条消息记录,然后入库,在写个接口供前台来拉取消息记录. 看到这个需求,首先 ...
- spring框架学习笔记7:事务管理及案例
Spring提供了一套管理项目中的事务的机制 以前写过一篇简单的介绍事务的随笔:http://www.cnblogs.com/xuyiqing/p/8430214.html 还有一篇Hibernate ...
- 【Spring Boot学习之五】切面日志管理
环境 eclipse 4.7 jdk 1.8 Spring Boot 1.5.2 一.log4j 常见方式:log4j.properties + org.apache.log4j.Logger比如:l ...
- Github点赞超多的Spring Boot学习教程+实战项目推荐!
Github点赞接近 100k 的Spring Boot学习教程+实战项目推荐! 很明显的一个现象,除了一些老项目,现在 Java 后端项目基本都是基于 Spring Boot 进行开发,毕竟它这 ...
- Spring Boot学习笔记2——基本使用之最佳实践[z]
前言 在上一篇文章Spring Boot 学习笔记1——初体验之3分钟启动你的Web应用已经对Spring Boot的基本体系与基本使用进行了学习,本文主要目的是更加进一步的来说明对于Spring B ...
- Spring Boot学习路线
Spring Boot 学习路线,本文计划根据作者近几年的工作.学习经验,来分析和制定一个学习使用 Spring Boot技术的步骤路线图. SpringBoot是伴随着Spring4.0诞生的: S ...
- 15 个优秀开源的 Spring Boot 学习项目,一网打尽!
Spring Boot 算是目前 Java 领域最火的技术栈了,松哥年初出版的 <Spring Boot + Vue 全栈开发实战>迄今为止已经加印了 8 次,Spring Boot 的受 ...
- 15 个优秀开源的 Spring Boot 学习项目
Spring Boot 算是目前 Java 领域最火的技术栈了,松哥年初出版的 <Spring Boot + Vue 全栈开发实战>迄今为止已经加印了 8 次,Spring Boot 的受 ...
随机推荐
- JZOJ 5462. 【NOIP2017提高A组冲刺11.8】好文章
5462. [NOIP2017提高A组冲刺11.8]好文章 (File IO): input:article.in output:article.out Time Limits: 1000 ms M ...
- 排序算法合集(Java)
整理了一下常用的排序算法,算法过程和示意图不详细讲,百度很多,只列代码,如有错误,还望大家指出. 1.冒泡排序 public static void bubbleSort(int[] a){ for( ...
- vncserver 启动停止方式
vnc启停方式:vncserver :1 ; vncserver -kill :1
- linux 查看CPU内存 网络 流量 磁盘 IO
使用vmstat命令来察看系统资源情况 在命令行方式下,如何查看CPU.内存的使用情况,网络流量和磁盘I/O? Q: 在命令行方式下,如何查看CPU.内存的使用情况,网络流量和磁盘I/O? A: 在命 ...
- 笔记-python-lib-re
笔记-python-lib-re 1. re模块简介 re模块提供了与perl类似的正则匹配功能. 要搜索的模式和字符串都可以是Unicode字符串(str)以及8位字符串(bytes).但 ...
- 笔记-算法-KMP算法
笔记-算法-KMP算法 1. KMP算法 KMP算法是一种改进的字符串匹配算法,KMP算法的关键是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的.具体实现就是实现一 ...
- Diycode开源项目 BaseApplication分析+LeakCanary第三方+CrashHandler自定义异常处理
1.BaseApplication整个应用的开始 1.1.看一下代码 /* * Copyright 2017 GcsSloop * * Licensed under the Apache Licens ...
- 16,Python网络爬虫之Scrapy框架(CrawlSpider)
今日概要 CrawlSpider简介 CrawlSpider使用 基于CrawlSpider爬虫文件的创建 链接提取器 规则解析器 引入 提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话, ...
- OpenCV学习笔记(五) 文件存取
转自输入输出XML和YAML文件 To be filled
- easyui datagrid复选框控制单选
使用easyui datagrid的时候,由于对数据表格操作太多,并且有单选和多选功能因此采用复选框.但是在单选的状态,使用CheckOnSelect和singleselect时发现,页面有明显延迟, ...