使用spring-data-jpa實(shí)現(xiàn)簡(jiǎn)單的兩表聯(lián)查實(shí)踐
spring-data-jpa實(shí)現(xiàn)簡(jiǎn)單的兩表聯(lián)查
關(guān)于Spring-data-jpa的配置+Springboot+Spring-data-jpa的簡(jiǎn)單操作簡(jiǎn)單操作+分布式服務(wù)設(shè)置一個(gè)永遠(yuǎn)不重復(fù)的ID
初學(xué)Spring套餐家族中的Spring-data-jpa發(fā)現(xiàn)可以更簡(jiǎn)單的實(shí)現(xiàn)一些基本的增刪改查,以下是一些基礎(chǔ)操作,希望可以給初學(xué)者一些幫助
spring家族
Spring Boot spring Cloud Spring framework Spring-data Spring data-jpa(簡(jiǎn)單的增刪改查)
jpa配置
jpa的底層是基于hibernate
多表聯(lián)查的時(shí)候會(huì)用到一對(duì)多,多對(duì)一的關(guān)系等
springboot一旦是一個(gè)web程序,記得配置數(shù)據(jù)源
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/studentdb?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&zeroDateTimeBehavior=CONVERT_TO_NULL
jpa:
database: mysql
hibernate:
ddl-auto: update
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
show-sql: true
profiles:
active: local實(shí)體類快速建表
@Data
@Entity
public class Student {
@Id
private Long stuid;
private String name;
private String sex;
@ManyToOne
private Grade grade;
}
Id列的注解
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) /*Id表示主鍵 主鍵有生成策略*/ /*GenerationType.IDENTITY唯一列還自動(dòng)增長(zhǎng)*/ /*GenerationType.AUTO自動(dòng)增長(zhǎng)*/ /*Oracle中是沒(méi)有自動(dòng)增長(zhǎng)的 設(shè)置GenerationType.SEQUENCE 使用序列進(jìn)行增長(zhǎng)*/ /*GeneratedValue 自動(dòng)增長(zhǎng)生成的value值*/
普通列注解
@Column
啟動(dòng)后自動(dòng)建表成功

Dao(數(shù)據(jù)訪問(wèn)層)接口
public interface StudentMapper extends JpaRepository<Student,Long>, JpaSpecificationExecutor<Student> {
}
ServiceImpl類
@Service
public class StudentServiceImpl {
@Autowired
private StudentMapper studentMapper;
public Page<Student> students(Integer pageNum, Integer size){
if(pageNum==null||pageNum<0){
pageNum=0;
}
if (size==null){
size=2;
}
return studentMapper.findAll(PageRequest.of(pageNum,size));
}
public void del(Long id){
try {
studentMapper.deleteById(id);
}catch (Exception e){
e.printStackTrace();
}
}
public Student getByid(Long id){
Optional<Student> byId = studentMapper.findById(id);
return byId.get();
}
public Student add(Student student){
return studentMapper.save(student);
}
public Student upd(Student student){
return studentMapper.save(student);
}
}
因?yàn)閕d我沒(méi)有給自增 所以要手動(dòng)給id并且不能重復(fù)
先創(chuàng)建工具類
public class IdWorker {
// 時(shí)間起始標(biāo)記點(diǎn),作為基準(zhǔn),一般取系統(tǒng)的最近時(shí)間(一旦確定不能變動(dòng))
private final static long twepoch = 1288834974657L;
// 機(jī)器標(biāo)識(shí)位數(shù)
private final static long workerIdBits = 5L;
// 數(shù)據(jù)中心標(biāo)識(shí)位數(shù)
private final static long datacenterIdBits = 5L;
// 機(jī)器ID最大值
private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 數(shù)據(jù)中心ID最大值
private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
// 毫秒內(nèi)自增位
private final static long sequenceBits = 12L;
// 機(jī)器ID偏左移12位
private final static long workerIdShift = sequenceBits;
// 數(shù)據(jù)中心ID左移17位
private final static long datacenterIdShift = sequenceBits + workerIdBits;
// 時(shí)間毫秒左移22位
private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
/* 上次生產(chǎn)id時(shí)間戳 */
private static long lastTimestamp = -1L;
// 0,并發(fā)控制
private long sequence = 0L;
private final long workerId;
// 數(shù)據(jù)標(biāo)識(shí)id部分
private final long datacenterId;
public IdWorker(){
this.datacenterId = getDatacenterId(maxDatacenterId);
this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
}
/**
* @param workerId
* 工作機(jī)器ID
* @param datacenterId
* 序列號(hào)
*/
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;
}
/**
* 獲取下一個(gè)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) {
// 當(dāng)前毫秒內(nèi),則+1
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
// 當(dāng)前毫秒內(nèi)計(jì)數(shù)滿了,則等待下一秒
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個(gè)低位
*/
return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
}
/**
* <p>
* 數(shù)據(jù)標(biāo)識(shí)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;
}
注入
@SpringBootApplication
public class SpringDataJpa01Application {
public static void main(String[] args) {
SpringApplication.run(SpringDataJpa01Application.class, args);
}
@Bean
public IdWorker sb(){
return new IdWorker();
}
}
調(diào)用新增方法是執(zhí)行

Controller(控制層)類
@Controller
public class StudentController {
@Autowired
private StudentServiceImpl studentService;
@Autowired
private GradeMapper gradeMapper;
@Autowired
private IdWorker idWorker;
@GetMapping("/students")
public String findAll(Integer pageNum, Integer size, Model model) {
Page<Student> students = studentService.students(pageNum, size);
model.addAttribute("students", students);
return "index";
}
@DeleteMapping("/student/{id}")
public String del(@PathVariable("id") Long id) {
studentService.del(id);
return "redirect:/students";
}
@GetMapping("/student")
public String edit(Long id, Model model) {
model.addAttribute("grades", gradeMapper.findAll());
if (id != null) {
model.addAttribute("students", studentService.getByid(id));
}
return "edit";
}
@PostMapping("/student")
public String add(Student student) {
student.setStuid(idWorker.nextId());
studentService.add(student);
return "redirect:/students";
}
@PutMapping("/student")
public String upd(Student student) {
studentService.upd(student);
return "redirect:/students";
}
}
index.html頁(yè)面
首頁(yè)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<a th:href="@{/student}" rel="external nofollow" >添加</a>
<form action="">
name:<input type="text">
<input type="submit" value="搜索">
</form>
<tr>
<td>#</td>
<td>姓名</td>
<td>性別</td>
<td>年級(jí)</td>
<td>操作</td>
</tr>
<tr th:each="stu : ${students}">
<td th:text="${stu.stuid}">#</td>
<td th:text="${stu.name}">姓名</td>
<td th:text="${stu.sex}">性別</td>
<td th:text="${stu.grade.name}">年級(jí)</td>
<td>
<button class="del" th:attr="del_uri=@{/student/}+${stu.stuid}">刪除</button>
<a th:href="@{/student(id=${stu.stuid})}" rel="external nofollow" >修改</a>
</td>
</tr>
</table>
<form id="DelFoem" action="" method="post">
<input type="hidden" name="_method" value="delete">
</form>
<a th:href="@{/students(pageNum=1)}" rel="external nofollow" >首頁(yè)</a>
<a th:href="@{/students(pageNum=${students.number}-1)}" rel="external nofollow" >上一頁(yè)</a>
<a th:if="${students.hasNext()}" th:href="@{/students(pageNum=${students.number}+1)}" rel="external nofollow" >下一頁(yè)</a>
<a th:if="${!students.hasNext()}" th:href="@{/students(pageNum=${students.totalPages}-1)}" rel="external nofollow" rel="external nofollow" >下一頁(yè)</a>
<a th:href="@{/students(pageNum=${students.totalPages}-1)}" rel="external nofollow" rel="external nofollow" >尾頁(yè)</a>
共[[${students.totalPages}]]頁(yè),當(dāng)前第[[${students.number}+1]]
</body>
<script type="text/javascript" th:src="@{/js/jquery-1.12.4.js}"></script>
<script type="text/javascript">
$(".del").click(function () {
$("#DelFoem").attr("action", $(this).attr("del_uri")).submit();
})
</script>
</html>添加修改頁(yè)面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<form th:action="@{/student}" method="post">
<input type="hidden" name="_method" value="put" th:if="${students!=null}">
<input type="hidden" name="stuid" th:value="${students?.stuid}" th:if="${students!=null}">
<tr>
<td>name:<input type="text" name="name" th:value="${students?.name}"></td>
</tr>
<tr>
<td>sex:<input type="text" name="sex" th:value="${students?.sex}"></td>
</tr>
<tr>
<td>grade:
<select name="grade.gradeId">
<option th:each="grade : ${grades}"
th:value="${grade.gradeId}"
th:text="${grade.name}"
th:selected="${students!=null&&students?.grade.gradeId==grade.gradeId}"></option>
</select></td>
</tr>
<tr>
<td>
<input type="submit" th:value="${students==null?'添加':'修改'}">
</td>
</tr>
</form>
</table>
</body>
</html>總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java讀取properties配置文件時(shí),出現(xiàn)中文亂碼的解決方法
下面小編就為大家?guī)?lái)一篇Java讀取properties配置文件時(shí),出現(xiàn)中文亂碼的解決方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-11-11
Java正則驗(yàn)證正整數(shù)的方法分析【測(cè)試可用】
這篇文章主要介紹了Java正則驗(yàn)證正整數(shù)的方法,結(jié)合實(shí)例形式對(duì)比分析了java針對(duì)正整數(shù)的驗(yàn)證方法及相關(guān)注意事項(xiàng),需要的朋友可以參考下2017-08-08
SpringBoot異步Async使用Future與CompletableFuture區(qū)別小結(jié)
本文主要介紹了SpringBoot異步Async使用Future與CompletableFuture區(qū)別小結(jié),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
使用Feign實(shí)現(xiàn)微服務(wù)間文件下載
這篇文章主要為大家詳細(xì)介紹了使用Feign實(shí)現(xiàn)微服務(wù)間文件下載,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04
Java8 Stream對(duì)兩個(gè) List 遍歷匹配數(shù)據(jù)的優(yōu)化處理操作
這篇文章主要介紹了Java8 Stream對(duì)兩個(gè) List 遍歷匹配數(shù)據(jù)的優(yōu)化處理操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08
springBoot連接遠(yuǎn)程Redis連接失敗的問(wèn)題解決
本文主要介紹了springBoot連接遠(yuǎn)程Redis連接失敗的問(wèn)題解決,使用springboot里面的redisTemplate進(jìn)行連接的時(shí)候,卻發(fā)生了報(bào)錯(cuò),下面就來(lái)一起解決一下2024-05-05

