Compare commits

...

8 Commits

Author SHA1 Message Date
81502c754b example 2024-11-05 11:52:55 +08:00
19254c73bf add img 2024-11-05 11:32:44 +08:00
ea19f7ba07 add example 2024-11-05 11:32:14 +08:00
529d237591 example 2024-11-05 11:28:53 +08:00
c446e028fd add datasource settings 2024-11-05 11:05:42 +08:00
e8bfa72e9a fix 2024-11-05 11:01:26 +08:00
6cfb52eb1b 重新组织本章内容 2024-11-05 11:00:08 +08:00
e2b3d0c76f rest 2024-11-05 09:26:27 +08:00
23 changed files with 1093 additions and 80 deletions

View File

@ -1037,8 +1037,37 @@ public class HelloController {
> **@RequestParam**注解用于获取HTTP请求中的查询参数例如?name=John&age=20。使用该注解可以将查询参数值绑定到对应的控制器方法的参数中并进行相应的业务操作。需要注意的是@RequestParam注解默认情况下是必需的即如果没有传递对应的查询参数则会抛出异常。如果想要将其设置为可选的可以在注解中添加required=false属性。
### 5.6 REST
### 5.6 构建工具
RESTRepresentational State Transfer表述性状态转移是一种设计风格而不是一种具体的协议或标准。它主要用于设计网络应用程序特别是那些通过HTTP协议进行通信的应用程序。RESTful架构有以下几个核心特点
- **资源Resources**
- 资源是API的核心概念通常是名词表示应用程序中的实体。例如用户、订单、产品等。
- 每个资源都有一个唯一的URI。
- **HTTP 方法HTTP Methods**
- **GET**:获取资源。
- **POST**:创建新资源或触发某个操作。
- **PUT**:更新现有资源。
- **DELETE**:删除资源。
- **PATCH**:部分更新资源。
- **状态码Status Codes**
- HTTP状态码用于指示请求的结果。常见的状态码包括
- **200 OK**:请求成功。
- **201 Created**:资源已创建。
- **204 No Content**:请求成功,但没有返回内容。
- **400 Bad Request**:请求无效。
- **401 Unauthorized**:未授权。
- **403 Forbidden**:禁止访问。
- **404 Not Found**:资源未找到。
- **500 Internal Server Error**:服务器内部错误。
- **内容协商Content Negotiation**
- 客户端可以通过Accept头指定期望的响应格式如JSON、XML等。
- 服务器根据客户端的请求返回适当格式的数据。
### 5.7 构建工具
构建工具Build Tools是软件开发过程中用于自动化构建、测试和打包软件应用程序的工具。它们通常用于编译源代码、运行测试、生成文档、打包应用程序以及执行其他与构建过程相关的任务。
@ -1059,9 +1088,9 @@ java项目常用的构建工具有
- 支持 Groovy 和 Kotlin 脚本,可以替代 Ant 和 Maven。
- 提供了丰富的插件生态系统。
#### 5.6.1 Maven
#### 5.7.1 Maven
##### 5.6.1.1 独立使用Maven
##### 5.7.1.1 独立使用Maven
##### 安装 Maven
@ -1097,7 +1126,7 @@ cd path/to/your/project
mvn clean package
mvn package
```
##### 5.6.1.2 在IDEA使用Maven
##### 5.7.1.2 在IDEA使用Maven
**导入 Maven 项目**
* 打开 IntelliJ IDEA
@ -1114,9 +1143,9 @@ IntelliJ IDEA 自带 Maven 插件,可以使用 Maven 插件来运行测试、
> **访问 Maven 工具窗口:** 在 IntelliJ IDEA 的右侧栏中找到 “Maven” 工具窗口。 如果没有显示,可以通过 “View” > “Tool Windows” > “Maven” 打开。
#### 5.6.2 Gradle
#### 5.7.2 Gradle
##### 5.6.2.1 独立使用Gradle
##### 5.7.2.1 独立使用Gradle
##### 安装 Gradle
@ -1161,7 +1190,7 @@ IntelliJ IDEA 自带 Maven 插件,可以使用 Maven 插件来运行测试、
- **清理项目**: `./gradlew clean` Linux/macOS
- `gradlew.bat clean` Windows
##### 5.6.2.2 IDEA中使用Gradle
##### 5.7.2.2 IDEA中使用Gradle
在 IntelliJ IDEA 中使用 Gradle 同样可以提高开发效率,因为 IDEA 提供了对 Gradle 的深度集成支持。以下是详细的步骤说明如何在 IntelliJ IDEA 中使用 Gradle

View File

@ -3,7 +3,7 @@
参考[jdbc(ppt)](./resources/JDBC.pptx)
### 6.1 JDBC(掌握)
### 6.1 JDBC(了解)
#### 6.1.1 什么是JDBC
- **定义**: JDBC (Java Database Connectivity) 是Java中用于连接和操作关系型数据库的标准API。
- **用途**: JDBC允许Java应用程序与各种关系型数据库进行交互包括执行SQL语句、处理查询结果等。
@ -164,7 +164,7 @@ public class JdbcCrudExample {
Connection conn = ds.getConnection();
```
### 6.3 SQL注入的预防措施(掌握)
### 6.3 SQL注入的预防措施(了解)
- **定义**: SQL注入是一种常见的安全攻击通过在SQL语句中插入恶意代码来破坏数据库。
- **预防**: 使用预编译语句PreparedStatement来防止SQL注入。
- **创建PreparedStatement对象**:
@ -177,9 +177,126 @@ public class JdbcCrudExample {
ResultSet rs = pstmt.executeQuery();
```
### 6.4 事务管理(了解)
### 6.4 ORM(了解)
#### 6.4.1 ORM基本概念
- **定义**: ORM (Object-Relational Mapping) 是一种编程技术,用于将对象模型映射到关系型数据库模型。
- **目的**: 简化数据库操作,提高开发效率。
#### 6.4.2 常见ORM框架介绍
- **JPA (Java Persistence API)**
- **定义**: JPA 是Java EE标准的一部分提供了一种对象持久化机制。
- **特点**: 支持实体管理和生命周期管理。
- **Hibernate**
- **定义**: Hibernate 是一个流行的ORM框架实现了JPA规范。
- **特点**: 提供了强大的映射能力和缓存机制。
- **MyBatis**
- **定义**: MyBatis 是一个半自动的ORM框架提供了SQL查询的灵活性。
- **特点**: 支持动态SQL和存储过程。
#### 6.4.1 事务管理的基本概念
#### 6.4.3 JPA (掌握)
> JPA的全称是Java Persistence API 即Java 持久化API是SUN公司推出的一套基于ORM的规范内部是由一系列的接口和抽象类构成。 JPA通过注解描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
>
> JPA本身不是ORM框架——因为JPA并未提供ORM实现它只是制订了ORM规范、API接口具体实现则由服务厂商来提供实现。
> 在Spring Boot中我们可以使用Spring Data JPA库来实现JPA。Spring Data JPA通过提供一系列接口和依赖注入的实现来简化与JPA的交互同时提供了自动配置和默认规则使得应用程序无需编写大量的代码就能实现数据的访问和操作。
![spring data jap](./resources/imgs/spring-data-jpa.png)
##### 理解实体类
在面向对象编程中,实体类是指具有某种功能或者意义的对象,可以是一个人、一件物品、一个地点、一项服务等。实体类通常由多个属性(字段)组成,并且可以具有多个操作(方法),来处理这些属性的修改、获取、设置等。
> 在ORM框架中实体类通常是指与数据库表相关联的Java类用于存储数据库表中的数据并提供了对这些数据进行操作的方法。这个类的所有属性通常与该表中的列相对应并具有相同的类型和名称。
下面是一个使用Java语言定义的User实体类的例子
```java
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
// getter and setters omitted for brevity
}
```
在此类定义中,使用@Entity和@Table注释来指定该类映射到数据库中的哪个表。该类中的id、username和password字段分别对应数据库表中的id、username和password列并使用@Column注释指定每个字段与表中的列之间的映射关系。在此示例中还使用@Id和@GeneratedValue注释表示id字段是主键自动递增产生。
##### 使用spring data jpa实现数据库访问层
在Spring Boot中Repository层是数据访问层的一种实现方式。它是一个在数据访问层中专注于对数据库进行访问、操作和管理的接口。
[
Repository层通常使用ORM框架例如Hibernate、MyBatis来与数据库进行交互并将实体类映射到数据库表中。Repository层的目标是隐藏与底层数据存储相关的细节使开发人员仅需关注业务逻辑并提供可扩展性和松散耦合性。
下面是一个简单的例子演示如何在Spring Boot中创建一个UserRepository]()
```java
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
```
> 上述代码定义了一个UserRepository接口该接口继承了JpaRepository并特定了实体类为User主键类型为Long。UserRepository中还定义了根据用户名查询用户信息的findByUsername方法。
> 在此例中我们使用JpaRepository提供的方法来实现基本的CRUD操作同时自定义findByUsername方法以满足我们的业务需求。
##### JpaRepository
JpaRepository接口继承了PagingAndSortingRepository和CrudRepository两个接口它包含了CRUD方法和分页/排序方法等常用操作如save、findById、findAll、deleteById和flush等。以下是JpaRepository的一些常用方法
- findOne根据主键查询单个实体。
- findById根据主键查询单个实体返回Optional类型结果。
- save保存或更新实体。
- deleteById根据主键删除实体。
- findAll查询所有实体列表。
- count统计实体数量。
- existsById判断是否存在指定主键的实体。
- flush立即将持久化上下文的挂起状态写入数据库。
JpaRepository还支持自定义查询方法这可以通过在接口中添加自定义方法来实现。自定义查询方法应使用@Query注解具有灵活性和可扩展性例如
```java
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.username = ?1 AND u.age = ?2")
List<User> findByUsernameAndAge(String username, Integer age);
}
```
以上代码中定义了一个查询方法findByUsernameAndAge使用@Query注解指定查询语句。参数值通过?1和?2进行占位并传入同时需要注意复合查询之间的关系。
##### Spring Boot项目中JPA的配置
在application.yml中配置JPA的属性如数据库连接信息、实体类包名、数据库类型等。示例如下
```yaml
spring:
jackson:
property-naming-strategy: SNAKE_CASE # 驼峰转下划线
datasource:
url: jdbc:mysql://localhost:3306/paopao?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true # MySQL连接URLpaopao是数据库名
driverClassName: com.mysql.cj.jdbc.Driver # MySQL的Driver类名
username: root # MySQL用户名
password: root # MySQL密码
jpa:
show-sql: true
open-in-view: false
defer-datasource-initialization: true
database-platform: org.hibernate.dialect.MySQL8Dialect # 修改为MySQL的Dialect
hibernate:
ddl-auto: update # 根据需要调整update适用于开发和某些生产环境
format_sql: true # 保持原样用于格式化SQL输出
```
### 6.5 事务管理(掌握)
#### 6.5.1 事务管理的基本概念
在计算机科学中特别是在数据库管理和分布式计算领域事务Transaction是一种基本的操作单位它确保了一系列操作要么全部成功要么全部失败。事务的概念是数据库管理系统DBMS中用来保证数据完整性和一致性的重要机制之一。
@ -190,7 +307,7 @@ public class JdbcCrudExample {
- **隔离性 (Isolation)**: 事务之间是隔离的,不会相互影响。
- **持久性 (Durability)**: 一旦事务提交,它的效果是持久的。
#### 6.4.2 Spring事务管理器
#### 6.5.2 Spring事务管理器
- **定义**: Spring提供了多种事务管理器如`DataSourceTransactionManager`。
- **示例**:
```java
@ -204,7 +321,7 @@ public class JdbcCrudExample {
}
```
#### 6.4.3 使用@Transactional进行声明式事务管理
#### 6.5.3 使用@Transactional进行声明式事务管理
- **定义**: 使用@Transactional注解来声明式地管理事务简化了事务控制代码。
- **示例**:
```java
@ -224,7 +341,7 @@ public class JdbcCrudExample {
}
```
#### 6.4.4 使用编程式事务管理
#### 6.5.4 使用编程式事务管理
- **定义**: 通过编程的方式显式地管理事务,适用于需要更细粒度控制事务的情况。
- **示例**:
```java
@ -253,26 +370,3 @@ public class JdbcCrudExample {
}
```
### 6.5 ORM(了解)
#### 6.5.1 ORM基本概念
- **定义**: ORM (Object-Relational Mapping) 是一种编程技术,用于将对象模型映射到关系型数据库模型。
- **目的**: 简化数据库操作,提高开发效率。
#### 6.5.2 常见ORM框架介绍
- **JPA (Java Persistence API)**
- **定义**: JPA 是Java EE标准的一部分提供了一种对象持久化机制。
- **特点**: 支持实体管理和生命周期管理。
- **Hibernate**
- **定义**: Hibernate 是一个流行的ORM框架实现了JPA规范。
- **特点**: 提供了强大的映射能力和缓存机制。
- **MyBatis**
- **定义**: MyBatis 是一个半自动的ORM框架提供了SQL查询的灵活性。
- **特点**: 支持动态SQL和存储过程。
### 6.6 NoSQL数据库(了解)
#### 6.6.1 MongoDB介绍
- **定义**: MongoDB 是一个文档型NoSQL数据库使用JSON-like文档存储数据。
- **特点**: 高性能、高可用性、易于水平扩展。
#### 6.6.2 Redis介绍
- **定义**: Redis 是一个开源的键值存储系统,支持多种数据结构。
- **特点**: 高性能、低延迟、持久化支持。
- **使用**: 存储会话数据、缓存、计数器等。

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

View File

@ -1,2 +1,2 @@
rootProject.name = 'spring-boot-application'
rootProject.name = 'spring-boot-web-demo'

View File

@ -1,26 +0,0 @@
package com.lk.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/hello")
public class HelloController {
@GetMapping
public String hello() {
return "Hello World";
}
@GetMapping("/json")
public Map<String,String> json() {
Map<String,String> data = new HashMap<>();
data.put("message","Hello World");
return data;
}
}

View File

@ -1,6 +1,8 @@
package com.lk.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

View File

@ -1,15 +1,12 @@
package com.lk.demo;
public class User {
private Long id;
private String name;
private String password;
private String email;
private String phone;
public User(String name, String email, String phone) {
this.name = name;
this.email = email;
this.phone = phone;
}
private Integer age;
public String getName() {
return name;
@ -34,4 +31,28 @@ public class User {
public void setPhone(String phone) {
this.phone = phone;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -1,10 +1,9 @@
package com.lk.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@ -12,10 +11,82 @@ import java.util.List;
public class UserController {
@Autowired
private UserService userService;
UserService userService;
/**
* 获取指定ID的用户信息
* Method: GET
* URL: /users/{id}
* 输入参数:
* - @PathVariable Long id: 用户ID
* 返回数据结构:
* - User对象包含id, name, age
*/
@GetMapping("/{id}")
public User getUser(@PathVariable Long id){
System.out.println("Got id from http request: " + id);
return userService.getUser(id);
}
/**
* 根据名称分页查询用户列表
* Method: GET
* URL: /users?name={name}&page={page}&pageSize={pageSize}
* 输入参数:
* - @RequestParam String name: 用户名称
* - @RequestParam int page: 当前页码
* - @RequestParam int pageSize: 每页大小
* 返回数据结构:
* - List<User> 用户列表每个User对象包含id, name, age
*/
@GetMapping("")
public List<User> index() {
return userService.getUsers();
public List<User> findUsers(@RequestParam("name") String name, @RequestParam int page, @RequestParam int pageSize){
System.out.println("Got name: " + name+ " page: " + page+ " pageSize: " + pageSize);
return userService.queryUsers();
}
/**
* 创建新用户
* Method: POST
* URL: /users
* 输入参数:
* - @RequestBody User user: 用户对象包含name, age, password,email
* 返回数据结构:
* - User对象包含id, name, age, password,email
*/
@PostMapping
public User createUser(@RequestBody User user){
System.out.println("Got name: "+user.getName()+ "pass:" +user.getPassword());
return userService.createUser(user);
}
/**
* 更新指定ID的用户信息
* Method: PUT
* URL: /users/{id}
* 输入参数:
* - @PathVariable Long id: 用户ID
* - @RequestBody User user: 用户对象包含name, age, password
* 返回数据结构:
* - User对象包含id, name, age, password
*/
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user){
System.out.println("Got id: "+id+ "name: "+user.getName()+ " pass:" +user.getPassword()+" age: "+user.getAge());
return userService.updateUser(id, user);
}
/**
* 删除指定ID的用户
* Method: DELETE
* URL: /users/{id}
* 输入参数:
* - @PathVariable Long id: 用户ID
* 返回数据结构:
* - String "ok" 表示删除成功
*/
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id){
System.out.println("delete id: "+id);
return "ok";
}
}

View File

@ -1,17 +1,48 @@
package com.lk.demo;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserService {
public List<User> getUsers(){
public User getUser(Long id){
User user = new User();
user.setId(id);
user.setName("lk");
user.setAge(18);
return user;
}
public List<User> queryUsers(){
List<User> users = new ArrayList<>();
users.add(new User("mike","mike@mail.com", "188111111"));
users.add(new User("john","john@mail.com", "133222222"));
users.add(new User("tom","tom@mail.com", "199222222"));
User u1 = new User();
u1.setName("John");
u1.setEmail("john@gmail.com");
u1.setPhone("123456789");
users.add(u1);
User u2 = new User();
u2.setName("Mike");
u2.setEmail("mike@gmail.com");
u2.setPhone("123456789");
users.add(u2);
return users;
}
public User createUser(User user){
user.setId(22L);
return user;
}
public User updateUser(Long id, User user){
user.setId(id);
return user;
}
}

View File

@ -0,0 +1,42 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

View File

@ -0,0 +1,35 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.3.5'
id 'io.spring.dependency-management' version '1.1.6'
}
group = 'com.lk.demo'
version = '1.0-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
repositories {
mavenLocal()
maven { url 'https://mirrors.cloud.tencent.com/nexus/repository/maven-public/' }
maven { url 'https://maven.aliyun.com/repository/central' }
maven { url 'https://maven.aliyun.com/repository/public' }
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
runtimeOnly 'com.mysql:mysql-connector-j'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
}
test {
useJUnitPlatform()
}

View File

@ -0,0 +1,6 @@
#Sat Oct 26 17:29:35 CST 2024
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,2 @@
rootProject.name = 'spring-boot-jpa-demo'

View File

@ -0,0 +1,107 @@
package com.lk.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcCrudExample {
private static final String DB_URL = "jdbc:mysql://localhost:3306/paopao";
private static final String USER = "root";
private static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
try {
// 加载MySQL驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 获取数据库连接
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 创建表
createTable(conn);
// 插入记录
insertUser(conn, "Alice", 28);
insertUser(conn, "Bob", 32);
// 查询记录
queryUsers(conn);
// 更新记录
updateUser(conn, "Alice", 29);
// 删除记录
deleteUser(conn, "Bob");
// 再次查询记录
queryUsers(conn);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private static void createTable(Connection conn) throws SQLException {
String sql = "CREATE TABLE IF NOT EXISTS users (" +
"id INT AUTO_INCREMENT PRIMARY KEY," +
"name VARCHAR(255) NOT NULL," +
"age INT)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.executeUpdate();
stmt.close();
}
private static void insertUser(Connection conn, String name, int age) throws SQLException {
String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.executeUpdate();
pstmt.close();
}
private static void queryUsers(Connection conn) throws SQLException {
String sql = "SELECT * FROM users";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
rs.close();
pstmt.close();
}
private static void updateUser(Connection conn, String name, int age) throws SQLException {
String sql = "UPDATE users SET age = ? WHERE name = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, age);
pstmt.setString(2, name);
int rowsUpdated = pstmt.executeUpdate();
System.out.println(rowsUpdated + " row(s) updated.");
pstmt.close();
}
private static void deleteUser(Connection conn, String name) throws SQLException {
String sql = "DELETE FROM users WHERE name = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
int rowsDeleted = pstmt.executeUpdate();
System.out.println(rowsDeleted + " row(s) deleted.");
pstmt.close();
}
}

View File

@ -0,0 +1,14 @@
package com.lk.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyWebApplication {
public static void main(String[] args) {
SpringApplication.run(MyWebApplication.class, args);
}
}

View File

@ -0,0 +1,74 @@
package com.lk.demo;
import jakarta.persistence.*;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String password;
@Column()
private String email;
@Column
private String phone;
@Column
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -0,0 +1,92 @@
package com.lk.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
UserService userService;
/**
* 获取指定ID的用户信息
* Method: GET
* URL: /users/{id}
* 输入参数:
* - @PathVariable Long id: 用户ID
* 返回数据结构:
* - User对象包含id, name, age
*/
@GetMapping("/{id}")
public User getUser(@PathVariable Long id){
System.out.println("Got id from http request: " + id);
return userService.getUser(id);
}
/**
* 根据名称分页查询用户列表
* Method: GET
* URL: /users?name={name}&page={page}&pageSize={pageSize}
* 输入参数:
* - @RequestParam String name: 用户名称
* - @RequestParam int page: 当前页码
* - @RequestParam int pageSize: 每页大小
* 返回数据结构:
* - List<User> 用户列表每个User对象包含id, name, age
*/
@GetMapping("")
public List<User> findUsers(@RequestParam("name") String name, @RequestParam int page, @RequestParam int pageSize){
System.out.println("Got name: " + name+ " page: " + page+ " pageSize: " + pageSize);
return userService.queryUsers();
}
/**
* 创建新用户
* Method: POST
* URL: /users
* 输入参数:
* - @RequestBody User user: 用户对象包含name, age, password,email
* 返回数据结构:
* - User对象包含id, name, age, password,email
*/
@PostMapping
public User createUser(@RequestBody User user){
System.out.println("Got name: "+user.getName()+ "pass:" +user.getPassword());
return userService.createUser(user);
}
/**
* 更新指定ID的用户信息
* Method: PUT
* URL: /users/{id}
* 输入参数:
* - @PathVariable Long id: 用户ID
* - @RequestBody User user: 用户对象包含name, age, password
* 返回数据结构:
* - User对象包含id, name, age, password
*/
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user){
System.out.println("Got id: "+id+ "name: "+user.getName()+ " pass:" +user.getPassword()+" age: "+user.getAge());
return userService.updateUser(id, user);
}
/**
* 删除指定ID的用户
* Method: DELETE
* URL: /users/{id}
* 输入参数:
* - @PathVariable Long id: 用户ID
* 返回数据结构:
* - String "ok" 表示删除成功
*/
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id){
System.out.println("delete id: "+id);
return userService.delete(id);
}
}

View File

@ -0,0 +1,6 @@
package com.lk.demo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}

View File

@ -0,0 +1,48 @@
package com.lk.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserService {
@Autowired
UserRepository userRepository;
public User getUser(Long id){
return userRepository.findById(id).orElse(null);
}
public List<User> queryUsers(){
return userRepository.findAll();
}
public User createUser(User user){
return userRepository.save(user);
}
public User updateUser(Long id, User user){
userRepository.findById(id).ifPresent(u->{
// u.setName(user.getName());
u.setPassword(user.getPassword());
u.setEmail(user.getEmail());
u.setPhone(user.getPhone());
u.setAge(user.getAge());
userRepository.save(u);
});
return userRepository.findById(id).orElse(null);
}
public String delete(Long id){
userRepository.deleteById(id);
return "ok";
}
}

View File

@ -0,0 +1,42 @@
spring:
jackson:
property-naming-strategy: SNAKE_CASE # 驼峰转下划线
datasource:
url: jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true # MySQL连接URLpaopao是数据库名
driverClassName: com.mysql.cj.jdbc.Driver # MySQL的Driver类名
username: root # MySQL用户名
password: root # MySQL密码
jpa:
show-sql: true
open-in-view: false
defer-datasource-initialization: true
database-platform: org.hibernate.dialect.MySQL8Dialect # 修改为MySQL的Dialect
hibernate:
ddl-auto: update # 根据需要调整update适用于开发和某些生产环境
format_sql: true # 保持原样用于格式化SQL输出
#
#spring:
#
# jackson:
# property-naming-strategy: SNAKE_CASE # 驼峰转下划线
#
# datasource:
# url: jdbc:h2:file:./demo.h2 # 使用文件存储
# driverClassName: org.h2.Driver
# username: root
# password: root
# h2:
# console: # 开启console访问 默认false
# enabled: true
# settings:
# trace: true # 开启h2 console 跟踪 方便调试 默认 false
# web-allow-others: true # 允许console 远程访问 默认false
# path: /h2 # h2 访问路径上下文
# jpa:
# show-sql: true
# open-in-view: false
# defer-datasource-initialization: true
# database-platform: org.hibernate.dialect.H2Dialect
# hibernate:
# ddl-auto: update