springDatejpa实现简单增删该查
1.首先勾选项目需要的依赖,页面渲染我选的是Thymeleaf
2.建好包和类
配置文件
server:
port: 8082
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springjpa?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: root
jpa:
show-sql: true #显示sql语句
hibernate:
ddl-auto: update
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
database: mysql #配置现在所使用的数据库
#配置spring-data-jpa
最终pox文件
<?xml version="1.0" encoding="UTF-8"?>
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.changan</groupId>
<artifactId>springdatajpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springdatajpa</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--spring-data-jpa的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--web项目的启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
实体类文件
package com.changan.springdatajpa.entity;
import lombok.Data;
import org.hibernate.annotations.GeneratorType;
import javax.persistence.*;
@Data
@Entity
@Table(name = "student")
public class Student {
@Id
//@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getGradeId() {
return gradeId;
}
public void setGradeId(Integer gradeId) {
this.gradeId = gradeId;
}
private String name;
private String sex;
private Integer gradeId;
}
DAO文件内容
package com.changan.springdatajpa.dao;
import com.changan.springdatajpa.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface StudentDao extends JpaRepository<Student,Long> {
//查询前两条
List<Student> findTop2By();
//根据姓名模糊查询
@Query(value = "select * from Student where name like concat('%',?,'%') ",nativeQuery = true)
List<Student> findByName(String name);
}
控制成内容
package com.changan.springdatajpa.controller;
import com.changan.springdatajpa.entity.Student;
import com.changan.springdatajpa.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
//@RestController
//@Controller+@ResponseBody 以json数据进行返回
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
/*restful风格实现*/
// 新增学生信息
@RequestMapping("/addStudent")
//@RequestMapping(method = RequestMethod.POST)
public String addStudent(Student student){
if(student.getId() == null){
studentService.save(student);
}else {
studentService.update(student);
}
return "redirect:/findStudent/1";
}
// 跳转新增页面
@RequestMapping("/goAddStudent")
public String goAddStudent(Model model){
Student student = new Student();
model.addAttribute("student",student);
return "student_add.html";
}
// 跳转修改页面
@RequestMapping("/findStudentById/{id}")
public String findStudentById(@PathVariable Long id,Model model){
Student student = this.studentService.findById(id);
model.addAttribute("student",student);
return "student_add.html";
}
// 删除学生信息
@RequestMapping("/delStudent/{id}")
public String delete(@PathVariable("id") Long id){
studentService.delete(id);
return "redirect:/findStudent/1";
}
// 分页查询
@RequestMapping("/findStudent/{page}")
public String findByPage(@PathVariable("page")Integer page, Model model){
Page<Student> students = studentService.findByPage(page);
model.addAttribute("students",students);
System.out.println( students.getNumber());
System.out.println(students.getTotalPages());
return "student.html";
}
}
Service实现内 内容
package com.changan.springdatajpa.service.impl;
import com.changan.springdatajpa.dao.StudentDao;
import com.changan.springdatajpa.entity.Student;
import com.changan.springdatajpa.service.StudentService;
import com.changan.springdatajpa.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Autowired
private IdWorker idWorker;
@Override
public Student save(Student student) {
//UUID
//把新增的对象返回给调用者
//分布式服务的时候很多时候会自己设置Id
return studentDao.save(student);
}
@Override
public List<Student> findAll() {
return studentDao.findAll();
}
@Override
public Student update(Student student) {
Student s = studentDao.save(student);
return s;
}
@Override
public void delete(Long id) {
studentDao.deleteById(id);
}
@Override
public Page<Student> findByPage(Integer page) {
if(page == null){
System.out.println("打手机大叔了肯德基啊数量单价拉萨孔家店阿斯顿撒旦撒啊实打实打算");
page = 1;
}
Integer size = 1;
PageRequest of = PageRequest.of(page-1, size);
Page<Student> pages = studentDao.findAll(of);
return pages;
}
@Override
public List<Student> findTop() {
return studentDao.findTop2By();
}
@Override
public Student findById(Long id) {
return studentDao.findById(id).get();
}
@Override
public List<Student> findByName(String name) {
return studentDao.findByName(name);
}
}
Service 接口代码
package com.changan.springdatajpa.service;
import com.changan.springdatajpa.entity.Student;
import org.springframework.data.domain.Page;
import java.util.List;
public interface StudentService {
Student save(Student student);
List<Student> findAll();
Student update(Student student);
void delete(Long id);
Page<Student> findByPage(Integer page);
List<Student> findTop();
Student findById(Long id);
List<Student> findByName(String name);
}
为了id唯一性 这里采用雪花算发生成唯一id
package com.changan.springdatajpa.util;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
/**
* <p>名称:IdWorker.java</p>
* <p>描述:分布式自增长ID</p>
* <pre>
* Twitter的 Snowflake JAVA实现方案
* </pre>
* 核心代码为其IdWorker这个类实现,其原理结构如下,我分别用一个0表示一位,用—分割开部分的作用:
* 1||0---0000000000 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000
* 在上面的字符串中,第一位为未使用(实际上也可作为long的符号位),接下来的41位为毫秒级时间,
* 然后5位datacenter标识位,5位机器ID(并不算标识符,实际是为线程标识),
* 然后12位该毫秒内的当前毫秒内的计数,加起来刚好64位,为一个Long型。
* 这样的好处是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由datacenter和机器ID作区分),
* 并且效率较高,经测试,snowflake每秒能够产生26万ID左右,完全满足需要。
* <p>
* 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加))
*
* @author Polim
*/
public class IdWorker {
// 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
private final static long twepoch = 1288834974657L;
// 机器标识位数
private final static long workerIdBits = 5L;
// 数据中心标识位数
private final static long datacenterIdBits = 5L;
// 机器ID最大值
private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 数据中心ID最大值
private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
// 毫秒内自增位
private final static long sequenceBits = 12L;
// 机器ID偏左移12位
private final static long workerIdShift = sequenceBits;
// 数据中心ID左移17位
private final static long datacenterIdShift = sequenceBits + workerIdBits;
// 时间毫秒左移22位
private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
/* 上次生产id时间戳 */
private static long lastTimestamp = -1L;
// 0,并发控制
private long sequence = 0L;
private final long workerId;
// 数据标识id部分
private final long datacenterId;
public IdWorker(){
this.datacenterId = getDatacenterId(maxDatacenterId);
this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
}
/**
* @param workerId
* 工作机器ID
* @param datacenterId
* 序列号
*/
public IdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
/**
* 获取下一个ID
*
* @return
*/
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
// 当前毫秒内,则+1
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
// 当前毫秒内计数满了,则等待下一秒
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
// ID偏移组合生成最终的ID,并返回ID
long nextId = ((timestamp - twepoch) << timestampLeftShift)
| (datacenterId << datacenterIdShift)
| (workerId << workerIdShift) | sequence;
return nextId;
}
private long tilNextMillis(final long lastTimestamp) {
long timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
/**
* <p>
* 获取 maxWorkerId
* </p>
*/
protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
StringBuffer mpid = new StringBuffer();
mpid.append(datacenterId);
String name = ManagementFactory.getRuntimeMXBean().getName();
if (!name.isEmpty()) {
/*
* GET jvmPid
*/
mpid.append(name.split("@")[0]);
}
/*
* MAC + PID 的 hashcode 获取16个低位
*/
return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
}
/**
* <p>
* 数据标识id部分
* </p>
*/
protected static long getDatacenterId(long maxDatacenterId) {
long id = 0L;
try {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
if (network == null) {
id = 1L;
} else {
byte[] mac = network.getHardwareAddress();
id = ((0x000000FF & (long) mac[mac.length - 1])
| (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
id = id % (maxDatacenterId + 1);
}
} catch (Exception e) {
System.out.println(" getDatacenterId: " + e.getMessage());
}
return id;
}
}