[读书笔记] 四、SpringBoot中使用JPA 进行快速CRUD操作
通过Spring提供的JPA Hibernate实现,进行快速CRUD操作的一个栗子~。
视图用到了SpringBoot推荐的thymeleaf来解析,数据库使用的Mysql,代码详细我会贴在下面文章中,请大家参考借鉴。
一、数据库表结构
CREATE TABLE `spring_jpa_test_table` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`message` TEXT NULL,
INDEX `id` (`id`)
)
ENGINE=InnoDB
;
二、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.springboot</groupId>
<artifactId>springboot_test1_1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>springboot_test1_1</name>
<url>http://maven.apache.org</url> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath />
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies> <build>
<finalName>my-spring-boot</finalName> <plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.6.RELEASE</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build> </project>
POM.xml
三、VO/PO
package core.vo; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table; @Entity
@Table(name = "spring_jpa_test_table")
public class JpaTestTablePO { private int id; private String message; @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} @Column(name = "message")
public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
}
}
JpaTestTablePO.java
四、DAO
package core.dao; import java.io.Serializable;
import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import core.vo.JpaTestTablePO; public interface JpaTestTableDao extends
JpaRepository<JpaTestTablePO, Serializable> { public List<JpaTestTablePO> findByMessageContaining(String message); }
JpaTestTableDao.java
五、Service
package core.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import core.dao.JpaTestTableDao;
import core.vo.JpaTestTablePO; @Service
public class TestService { @Autowired
JpaTestTableDao jpaTestTableDao; // SpringBoot JPA 默认CRUD实现
public void save(JpaTestTablePO po) {
jpaTestTableDao.save(po);
} public List<JpaTestTablePO> list() {
return jpaTestTableDao.findAll();
} public void delete(int id) {
jpaTestTableDao.delete(id);
} // SpringBoot JPA 简单查询
public List<JpaTestTablePO> findByMessageContaining(String message) {
return jpaTestTableDao.findByMessageContaining(message);
} }
TestService.java
六、Controller
package core; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; import core.service.TestService;
import core.vo.JpaTestTablePO; @Controller
public class HomePageController { @Autowired
TestService service; @RequestMapping(value = "/home", method = RequestMethod.GET)
public String toIndex(Map<String, Object> model) {
model.put("pos", service.list());
return "index";
} @RequestMapping(value = "/home", method = RequestMethod.POST)
public String toIndex2(JpaTestTablePO po, Map<String, Object> model) {
model.put("pos", service.findByMessageContaining(po.getMessage()));
return "index";
} @RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(JpaTestTablePO po) {
service.save(po);
return new ModelAndView("redirect:/home");
} @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public ModelAndView delete(@PathVariable("id") String id) {
service.delete(Integer.parseInt(id));
return new ModelAndView("redirect:/home");
}
}
HomePageController.java
七、application.properties
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy # stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect #spring.thymeleaf.prefix=classpath:/templates/
#spring.thymeleaf.suffix=.html
#spring.thymeleaf.mode=HTML5
#spring.thymeleaf.encoding=UTF-8
# ;charset=<encoding> is added
#spring.thymeleaf.content-type=text/html
# set to false for hot refresh spring.thymeleaf.cache=false
application.properties
八、index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<script
src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.txtChange = function() { }
});
</script>
</head>
<body>
<p th:text="${hello}"></p>
<!-- SEARCH TABLE -->
<form action="http://localhost:8080/home" method="post">
<p>
Search Condition: <input type="text" name="message"/> <input type="submit" value="Search" />
</p>
</form> <br />
<table border="1" width="400">
<tr>
<th colspan="3" align="center">Messages</th>
</tr>
<tr>
<td>Id</td>
<td>Message</td>
<td>Opt</td>
</tr>
<tr th:each="m,index: ${pos}">
<td th:text="${index.index}+1"></td>
<td th:text="${m.message}"></td>
<td><a th:href="'/delete/' + ${m.id }">delete</a></td>
</tr>
</table>
<br /> <div ng-app="myApp">
<div ng-controller="myCtrl">
<form action="http://localhost:8080/save" method="post">
<p>
Message: <input type="text" name="message" ng-model="message"
ng-blur="txtChange();" /> <input type="submit"
value="Save" />
</p>
</form>
</div>
</div>
</body> </html>
index.html
项目目录结构:

[读书笔记] 四、SpringBoot中使用JPA 进行快速CRUD操作的更多相关文章
- 【转】Verilog HDL常用建模方式——《Verilog与数字ASIC设计基础》读书笔记(四)
Verilog HDL常用建模方式——<Verilog与数字ASIC设计基础>读书笔记(四) Verilog HDL的基本功能之一是描述可综合的硬件逻辑电路.所谓综合(Synthesis) ...
- 【转载】MDX Step by Step 读书笔记(四) - Working with Sets (使用集合)
1. Set - 元组的集合,在 Set 中的元组用逗号分开,Set 以花括号括起来,例如: { ([Product].[Category].[Accessories]), ([Product].[ ...
- SpringBoot学习笔记(9)----SpringBoot中使用关系型数据库以及事务处理
在实际的运用开发中,跟数据库之间的交互是必不可少的,SpringBoot也提供了两种跟数据库交互的方式. 1. 使用JdbcTemplate 在SpringBoot中提供了JdbcTemplate模板 ...
- how tomcat works 读书笔记四 tomcat的默认连接器
事实上在第三章,就已经有了连接器的样子了,只是那仅仅是一个学习工具,在这一章我们会開始分析tomcat4里面的默认连接器. 连接器 Tomcat连接器必须满足下面几个要求 1 实现org.apache ...
- SpringBoot学习笔记(10)-----SpringBoot中使用Redis/Mongodb和缓存Ehcache缓存和redis缓存
1. 使用Redis 在使用redis之前,首先要保证安装或有redis的服务器,接下就是引入redis依赖. pom.xml文件如下 <dependency> <groupId&g ...
- 读书笔记《SpringBoot编程思想》
目录 一. springboot总览 1.springboot特性 2.准备运行环境 二.理解独立的spring应用 1.应用类型 2.@RestController 3.官网创建springboot ...
- 【记】《.net之美》之读书笔记(二) C#中的泛型
前言 上一篇读书笔记,很多小伙伴说这本书很不错,所以趁着国庆假期,继续我的读书之旅,来跟随书中作者一起温习并掌握第二章的内容吧. 一.理解泛型 1.为什么要使用泛型?-----通过使用泛型,可以极大地 ...
- SpringBoot学习笔记(4)----SpringBoot中freemarker、thymeleaf的使用
1. freemarker引擎的使用 如果你使用的是idea或者eclipse中安装了sts插件,那么在新建项目时就可以直接指定试图模板 如图: 勾选freeMarker,此时springboot项目 ...
- MyBatis-Plus学习笔记(1):环境搭建以及基本的CRUD操作
MyBatis-Plus是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,使用MyBatis-Plus时,不会影响原来Mybatis方式的使用. SpringBoot+M ...
随机推荐
- 【NOI复习】树链剖分
简介 树链剖分通常用来解决一类维护静态树上路径信息的问题, 例如:给定一棵点带权树, 接下来每次操作会修改某条路径上所有点的权值(修改为同一个值或是同加上一个值等) , 以及询问某条路径上所有点的权值 ...
- python学习好文
摘要: 学习别人的学习历程. 一 iTech的博客 http://www.cnblogs.com/itech/archive/2011/01/31/1948265.html
- centos7修改网卡名称
[root@localhost ~]# cd /etc/sysconfig/network-scripts/[root@localhost network-scripts]# mv ifcfg-eno ...
- oAuth 认证
这段时间公司开发项目用到oAuth2协议,现在做一下梳理. CORS即Cross Origin Resouce Share,跨域资源共享:是W3C为防止脚本攻击,而制定的安全标准之一,它云溪浏览器向跨 ...
- 安装nginx+ngx_lua支持WAF防护功能
安装nginx+ngx_lua支持WAF防护功能 nginx lua模块淘宝开发的nginx第三方模块,它能将lua语言嵌入到nginx配置中,从而使用lua就极大增强了nginx的能力.nginx以 ...
- POJ--1088--dp--滑雪
#include<iostream> using namespace std; ; }; }; int dp(int,int); int row,col; int main() { whi ...
- centos7用户,组及文件权限管理
centos7安装过程中如果没有创建用户的话,默认只有ROOT用户,这个用户是具有最高权限的帐户,可以做任何事情,但实际生产环境中我们一般不会使用这个用户,因为权限太大了,很危险. 所以在生产环境中就 ...
- Python巡检Oracle表空间并邮件告警
最近,自学了Python基础,突发奇想,把以前通过shell自定义通过nagios实现Oracle表空间以及ASM以及备份的脚本改进下,首先感叹的是Python脚本看上去确实挺好的,效率还不错. 这是 ...
- Spring 并发访问的线程安全性问题
首先对于spring的IOC来说,对象是由Spring来帮我们管理,也就是在Spring启动的时候,在Spring容器中,由Spring给我们创建的,Spring会帮我们维护,一般都是单例的,也就是一 ...
- LGTB与序列 状压dp
考试一看我就想到了状压dp.当时没有想到素数,以为每一位只有0~9这些数,就开始压了.后来发现是小于30,然后改到了15,发现数据一点不给面子,一个小点得数都没有,完美爆零.. 考虑到bi最多变成58 ...