通过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"/>&nbsp;&nbsp;<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();" />&nbsp;&nbsp;<input type="submit"
value="Save" />
</p>
</form>
</div>
</div>
</body> </html>

index.html

项目目录结构:

[读书笔记] 四、SpringBoot中使用JPA 进行快速CRUD操作的更多相关文章

  1. 【转】Verilog HDL常用建模方式——《Verilog与数字ASIC设计基础》读书笔记(四)

    Verilog HDL常用建模方式——<Verilog与数字ASIC设计基础>读书笔记(四) Verilog HDL的基本功能之一是描述可综合的硬件逻辑电路.所谓综合(Synthesis) ...

  2. 【转载】MDX Step by Step 读书笔记(四) - Working with Sets (使用集合)

    1. Set  - 元组的集合,在 Set 中的元组用逗号分开,Set 以花括号括起来,例如: { ([Product].[Category].[Accessories]), ([Product].[ ...

  3. SpringBoot学习笔记(9)----SpringBoot中使用关系型数据库以及事务处理

    在实际的运用开发中,跟数据库之间的交互是必不可少的,SpringBoot也提供了两种跟数据库交互的方式. 1. 使用JdbcTemplate 在SpringBoot中提供了JdbcTemplate模板 ...

  4. how tomcat works 读书笔记四 tomcat的默认连接器

    事实上在第三章,就已经有了连接器的样子了,只是那仅仅是一个学习工具,在这一章我们会開始分析tomcat4里面的默认连接器. 连接器 Tomcat连接器必须满足下面几个要求 1 实现org.apache ...

  5. SpringBoot学习笔记(10)-----SpringBoot中使用Redis/Mongodb和缓存Ehcache缓存和redis缓存

    1. 使用Redis 在使用redis之前,首先要保证安装或有redis的服务器,接下就是引入redis依赖. pom.xml文件如下 <dependency> <groupId&g ...

  6. 读书笔记《SpringBoot编程思想》

    目录 一. springboot总览 1.springboot特性 2.准备运行环境 二.理解独立的spring应用 1.应用类型 2.@RestController 3.官网创建springboot ...

  7. 【记】《.net之美》之读书笔记(二) C#中的泛型

    前言 上一篇读书笔记,很多小伙伴说这本书很不错,所以趁着国庆假期,继续我的读书之旅,来跟随书中作者一起温习并掌握第二章的内容吧. 一.理解泛型 1.为什么要使用泛型?-----通过使用泛型,可以极大地 ...

  8. SpringBoot学习笔记(4)----SpringBoot中freemarker、thymeleaf的使用

    1. freemarker引擎的使用 如果你使用的是idea或者eclipse中安装了sts插件,那么在新建项目时就可以直接指定试图模板 如图: 勾选freeMarker,此时springboot项目 ...

  9. MyBatis-Plus学习笔记(1):环境搭建以及基本的CRUD操作

    MyBatis-Plus是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,使用MyBatis-Plus时,不会影响原来Mybatis方式的使用. SpringBoot+M ...

随机推荐

  1. pyqt5 在qt designer后以弹窗的方式连接多个UI图形界面

    当我们通过pyqt开发时,eric6为我们提供了一个方便的工具:图形化的绘制UI工具--qt designer. 我们可以通过它开发多个UI,然后利用信号-槽工具,将功能代码附着在上面.也可以将多个界 ...

  2. Java 9 揭秘(19. 平台和JVM日志)

    Tips 做一个终身学习的人. 在这章中,主要介绍以下内容: 新的平台日志(logging)API JVM日志的命令行选项 JDK 9已经对平台类(JDK类)和JVM组件的日志系统进行了大整. 有一个 ...

  3. 记Angular与Django REST框架的一次合作(2):前端组件化——Angular

    注:这是这个系列的第二部分,主要集中在Angular的使用方面.之前使用过AngularJS(Angular 1.x),混在Django的模板中使用,这些页面一般完全是结果展示页.在有Django表单 ...

  4. PyCharm中Directory与Python package的区别

    对于Python而言,有一点是要认识明确的,python作为一个相对而言轻量级的,易用的脚本语言(当然其功能并不仅限于此,在此只是讨论该特点),随着程序的增长,可能想要把它分成几个文件,以便逻辑更加清 ...

  5. jvm参数解析(含调优过程)

    前阵       对底层账单系统进行了压测调优,调优的最后一步--jvm启动参数中,减小了线程的堆栈空间:-XX:ThreadStackSize=256K,缩减至原来的四分之一,效果明显,不过并没有调 ...

  6. Apache Kafka系列(二) 命令行工具(CLI)

    Apache Kafka命令行工具(Command Line Interface,CLI),下文简称CLI. 1. 启动Kafka 启动Kafka需要两步: 1.1. 启动ZooKeeper [roo ...

  7. C#设计模式(3)-工厂方法模式

    引言 上一篇介绍了设计模式中的简单工厂模式-C#设计模式(2)-简单工厂模式,本篇将介绍工厂方法模式,在简单工厂模式下进行改造: 工厂方法模式简介 工厂方法(FactoryMethod)模式:定义一个 ...

  8. 使用MySQL-Proxy读写分离时的注意事项

    在动手操作前最好先安装好MySQL-Proxy,并配置好MySQL主从服务器.补充:新版MySQL已经内建支持 延迟问题 读写分离不能回避的问题之一就是延迟,可以考虑Google提供的SemiSync ...

  9. c# 数组简述

    数组的声明与赋值:int[] a=new int[6]; 数组初始化器:int[] a=new int[2]{1,3}; 数组初始化器简化版:int[] a={1,3}; 数组初始值: 数字类型: 0 ...

  10. Python正则匹配

    使用Re模块 首先生成一个匹配模式pattern,如pattern='.test' 然后使用re.match(pattern,str)或者search()匹配调用 match跟search的区别: m ...