pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>

application.properties

#
server.address=0.0.0.0
server.port=8080
server.servlet.context-path=/test
server.session.timeout=300
server.error.path=/error
# Tomcat的访问日志,便于进行用户访问日志分析
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.buffered=true
server.tomcat.accesslog.directory=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/logs
# JSON解析的配置
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Asia/Shanghai
#
spring.thymeleaf.cache=true
spring.thymeleaf.enabled=true
# 文件上传配置
file.upload.path=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/fileUpLoad
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=0
spring.servlet.multipart.location=D:/Project/JavaWeb/SpringBoot/04JPASpringBoot/temp
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.resolve-lazily=false spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# MySQL新的连接字符串(加了时区)

spring.datasource.druid.one.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false

spring.datasource.druid.one.username=root
spring.datasource.druid.one.password=gis
# MySQL新的驱动
spring.datasource.druid.one.driver-class-name=com.mysql.cj.jdbc.Driver ##Druid
spring.datasource.druid.one.initial-size=2
spring.datasource.druid.one.max-active=5
spring.datasource.druid.one.min-idle=1
spring.datasource.druid.one.max-wait=60000
spring.datasource.druid.one.pool-prepared-statements=true
spring.datasource.druid.one.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.one.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.one.validation-query-timeout=60000
spring.datasource.druid.one.test-on-borrow=false
spring.datasource.druid.one.test-on-return=false
spring.datasource.druid.one.test-while-idle=true
spring.datasource.druid.one.time-between-eviction-runs-millis=60000
spring.datasource.druid.one.min-evictable-idle-time-millis=100000
#spring.datasource.druid.one.max-evictable-idle-time-millis=
spring.datasource.druid.one.filters=stat,wall,log
spring.datasource.druid.one.logSlowSql=true

数据库连接池的配置

package com.smartmap.sample.test.conf;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; @Configuration
public class DataSourceConfiguration { private final Log logger = LogFactory.getLog(DataSourceConfiguration.class); @Primary
@Bean
@ConfigurationProperties("spring.datasource.druid.one") # 这样配置可以支持后面的多数据源的情况
public DataSource getDataSourceConfiguration() {
return DruidDataSourceBuilder.create().build();
}
}

强大的JpaRepository

package com.smartmap.sample.test.dao;

import java.util.Date;
import java.util.List;
import java.util.Set; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query; import com.smartmap.sample.test.entity.User; public interface UserRepository extends JpaRepository<User, Long> {
// 基于Spring的方法名字查询
public User findByName(String name); public List<User> findByCreateTimeGreaterThan(Date createTime); // JPQL 查询
@Query(value="select u from user u where u.name=?1 and u.department.id=?2", nativeQuery=true)
public User findUser(String name, Long departmentId); // JPQA + 命名
@Query(value="select u from user u where u.name=:name and u.department.id=:departmentId", nativeQuery=true)
public User findUser2(String name, Long departmentId); // SQL 查询
@Query(value="select id, name, create_time, department_id from user where name=:name and department_id=:departmentId", nativeQuery=true)
public User findUserNativeQuery2(String name, Long departmentId); // SQL + 命名
@Query(value="select department_id, count(*) count from user group by department_id", nativeQuery= true)
public List<Object[]> queryUserCount(); // 分页配合使用
@Query(value="select u from user u where u.department.id=?1", nativeQuery=true)
public Page<User> queryUsers(Long departmentId, Pageable page); // 修改
@Modifying
@Query("update User u set u.name=?1 where u.id=?2")
public int updateName(String name, Long id); }

实体User

package com.smartmap.sample.test.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import com.fasterxml.jackson.annotation.JsonBackReference; @Entity
public class User { @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; @Column
private String name; @JsonBackReference // 防止相互引用,出现无限引用递归
@ManyToOne
@JoinColumn(name = "department_id")
private Department department; @Column(name = "create_time")
private Date createTime; public User() {
} public User(Long id, String name, Department department, Date createTime) {
super();
this.id = id;
this.name = name;
this.department = department;
this.createTime = createTime;
} public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Department getDepartment() {
return department;
} public void setDepartment(Department department) {
this.department = department;
} public Long getDepartmentId() {
return this.department == null ? null : this.department.getId();
} public void setDepartmentId(Long departmentId) {
if (this.department != null) {
this.department.setId(departmentId);
}
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} }

实体Department

package com.smartmap.sample.test.entity;

import java.util.HashSet;
import java.util.Set; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany; import com.fasterxml.jackson.annotation.JsonManagedReference; @Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; @Column
private String name; @JsonManagedReference // 防止相互引用,出现无限引用递归
@OneToMany(mappedBy = "department")
private Set<User> users = new HashSet<User>(); public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Set<User> getUsers() {
return users;
} public void setUsers(Set<User> users) {
this.users = users;
} }

Serivce类

package com.smartmap.sample.test.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.smartmap.sample.test.dao.UserRepository;
import com.smartmap.sample.test.entity.User;
import com.smartmap.sample.test.service.UserService; @Service
@Transactional
public class UserServiceImpl implements UserService { @Autowired
UserRepository userRepository; public Long addUser(User user) {
userRepository.save(user);
Long id = user.getId();
user.setName(user.getName() + "-" + "1");
userRepository.save(user);
return id;
} public List<User> getUsersSorted() {
Sort sort = Sort.by(Order.asc("id"));
return userRepository.findAll(sort);
} public List<User> getAllUsers(int page, int size){
Sort sort = Sort.by(Order.asc("id"));
PageRequest pageRequest = PageRequest.of(page, size, sort);
Page<User> pageUser = userRepository.findAll(pageRequest);
int totalPage = pageUser.getTotalPages();
long count = pageUser.getTotalElements();
return pageUser.getContent();
} @Override
public List<User> allUser() {
/*
* List<User> userList = new LinkedList<User>(); userList.add(new User("123",
* "root"));
*/ return userRepository.findAll();
} @Override
public User getUserById(Long userId) {
/* return new User("123", "root"); */ return userRepository.findById(userId).orElse(null);
} @Transactional
@Override
public User save(User user) {
/* return new User("123", "root"); */
return userRepository.save(user); } @Override
public int delete(Long userId) {
/* return 1; */
userRepository.deleteById(userId);
return 1;
} }

RestController类

package com.smartmap.sample.test.controller.rest;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.smartmap.sample.test.entity.User;
import com.smartmap.sample.test.service.UserService; @RestController
@RequestMapping("/api/v1.1/system/user")
public class UserRestController {
private final Log logger = LogFactory.getLog(UserRestController.class); @Autowired
UserService userService; /**
* 查询所有用户
*
* curl -XGET 'http://127.0.0.1:8080/api/v1.1/system/user/'
*
* @return
*/
@GetMapping("/")
public List<User> getAllUsers() {
return userService.allUser();
} /**
* 根据Id查询用户
*
* curl -XGET 'http://127.0.0.1:8080/api/v1.1/system/user/123'
*
* @param userId
* @return
*/
@GetMapping("/{userId}")
public User getUserById(@PathVariable("userId") Long userId) {
return userService.getUserById(userId);
} /**
* 翻页查询用户
*
* curl -XGET
* 'http://127.0.0.1:8080/api/v1.1/system/user/query?offset=123&limit=456&sortBy=789&sortOrder=456'
*
* @param offset
* @param limit
* @param sortBy
* @param sortOrder
* @return
*/
@GetMapping("/query")
public List<User> queryUserById(@RequestParam("offset") int offset, @RequestParam("limit") int limit,
@RequestParam("sortBy") int sortBy, @RequestParam("sortOrder") int sortOrder) {
logger.info(String.valueOf(offset));
logger.info(String.valueOf(limit));
logger.info(String.valueOf(sortBy));
logger.info(String.valueOf(sortOrder));
return userService.allUser();
} /**
* 添加用户
*
* curl -XPOST 'http://127.0.0.1:8080/test/api/v1.1/system/user/'
* -H'Content-type:application/json;charset=UTF-8' -d ' { "name":"123",
* "createTime":"2017-01-01 00:00:00", "departmentId":"9" }'
*
* @param user
* @return
*/
@PostMapping("/")
public User addUse(@RequestBody User user) {
System.out.println(user.getName());
return userService.save(user);
} /**
* 更新用户
*
* curl -XPUT 'http://127.0.0.1:8080/api/v1.1/system/user/'
* -H'Content-type:application/json;charset=UTF-8' -d ' { "id": "123",
* "name":"123" } '
*
* @param user
* @return
*/
@PutMapping("/")
public User updateUse(@RequestBody User user) {
return userService.save(user);
} /**
* 删除用户
*
* curl -XDELETE 'http://127.0.0.1:8080/api/v1.1/system/user/123'
*
* @param userId
* @return
*/
@DeleteMapping("/{userId}")
public String deleteUser(@PathVariable("userId") Long userId) {
if (userService.delete(userId) > 0) {
return "{success:true, message:'delete success'}";
} else {
return "{success:false, message:'delete fail'}";
}
} }

Spring Boot—15SpringJPA的更多相关文章

  1. 玩转spring boot——快速开始

    开发环境: IED环境:Eclipse JDK版本:1.8 maven版本:3.3.9 一.创建一个spring boot的mcv web应用程序 打开Eclipse,新建Maven项目 选择quic ...

  2. 【微框架】之一:从零开始,轻松搞定SpringCloud微框架系列--开山篇(spring boot 小demo)

    Spring顶级框架有众多,那么接下的篇幅,我将重点讲解SpringCloud微框架的实现 Spring 顶级项目,包含众多,我们重点学习一下,SpringCloud项目以及SpringBoot项目 ...

  3. 玩转spring boot——开篇

    很久没写博客了,而这一转眼就是7年.这段时间并不是我没学习东西,而是园友们的技术提高的非常快,这反而让我不知道该写些什么.我做程序已经有十几年之久了,可以说是彻彻底底的“程序老炮”,至于技术怎么样?我 ...

  4. 玩转spring boot——结合redis

    一.准备工作 下载redis的windows版zip包:https://github.com/MSOpenTech/redis/releases 运行redis-server.exe程序 出现黑色窗口 ...

  5. 玩转spring boot——AOP与表单验证

    AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...

  6. 玩转spring boot——结合JPA入门

    参考官方例子:https://spring.io/guides/gs/accessing-data-jpa/ 接着上篇内容 一.小试牛刀 创建maven项目后,修改pom.xml文件 <proj ...

  7. 玩转spring boot——结合JPA事务

    接着上篇 一.准备工作 修改pom.xml文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

  8. 玩转spring boot——结合AngularJs和JDBC

    参考官方例子:http://spring.io/guides/gs/relational-data-access/ 一.项目准备 在建立mysql数据库后新建表“t_order” ; -- ----- ...

  9. 玩转spring boot——结合jQuery和AngularJs

    在上篇的基础上 准备工作: 修改pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

随机推荐

  1. 【NOIP2013】 火柴排队 贪心+splay

    这题为啥我写得这么复杂. 首先我们不难发现,我们将序列$a$和序列$b$排序,考虑两序列内无相同元素,那么最小值显然为$\sum_{i=1}^{n} (a_i-b_i)^2$. 下面考虑做法 首先,我 ...

  2. 用Python玩转数据——第五周数据统计和可视化

    一.数据获取 1.本地数据 with 语句,pd.read_csv('data.csv') 2.网站上数据 2.1 直接获取网页源码,在用正则表达式进行删选 2.2 API接口获取---以豆瓣为例 i ...

  3. 对Deeplung检测+两样性分类的一个整合

    整体的流程分为以下几步: 读取原始数据(.mhd文件)——> 生成mask ——> 对数据预处理 ——> 执行检测 ——> 对检测结果进行分类 ——>可视化 懒一点,不贴 ...

  4. if嵌套语句 shell脚本实例 测试是否闰年

    在 if 语句里面,你可以使用另外一个 if 语句.只要你能逻辑管理 你就可以使用多层嵌套. 以下是一个测试闰年的例子: #!/bin/bash # This script will test if ...

  5. RHCE 学习结构

    本文内容为本站的 blog 链接 第一章   安装初体验 第二章   访问系统 2.1 基于图形化界面访问 2.2 基于文本访问 2.3 用户管理 第三章   文件系统 3.1  Linux 文件系统 ...

  6. MySQl资料链接

    原文:http://www.uml.org.cn/sjjm/sjjm-MySql.asp MySQl   MySQL高可用数据库内核深度优化的四重定制   MySQL数据表存储引擎类型及特性   My ...

  7. 下拉菜单;手风琴;九宫格的Jquery的使用实例

    下拉菜单;手风琴;九宫格的Jquery的使用实例 1.下拉菜单 效果如图: 代码如下: <!DOCTYPE html> <html lang="en"> & ...

  8. 【转】Hadoop vs Spark性能对比

    原文地址:http://www.cnblogs.com/jerrylead/archive/2012/08/13/2636149.html 基于Spark-0.4和Hadoop-0.20.2 1. K ...

  9. Python -- 网络编程 -- Socket发送文件

    客户端如果直接send两次,一次发文件名,一次发文件内容 服务端接受的时候会一起接收,不知怎么分开发送,或者分开接收, 或者全部接收再解析内容 今天发现传送mp3文件的时候没问题,传送文本文件的话,以 ...

  10. 数据库--oracle安装配置(本地安装的步骤及各种问题解决方案)

    oracle版本:Oracle 11g 本地电脑配置:安装内存8G 64为操作系统win8.1 下载Oracle 11g压缩包: 1 网址http://www.oracle.com/technetwo ...