我的gitee項目位址:https://gitee.com/hgqstudy/hgqstudy.git
文章目錄
-
-
-
- 1. 建立一個Spring Boot 項目
- 2. 建立資料庫
- 3. 在pom.xml檔案中引入maven依賴
- 4. 編寫application.properties檔案
- 5. 配置Swagger
- 6. 編寫Json工具類,主要是把資料轉為json格式
- 7. 編寫WebMvcConfig
- 8. 主啟動類編寫
- 9. 使用者實體類(CUserEntity)
- 10. 位址實體類(CAddressEntity)
- 11. 編寫CUserEntityRepository
- 12. 編寫CAddressEntityRepository
- 13. 編寫UserMessageWebController
- 14. 編寫UserAddressWebController
- 15. 最後測試一下
- 16. 總結
-
-
1. 建立一個Spring Boot 項目
File -> New -> Project -> Spring Initializr -> Next -> Next -> Next ->Finish
2. 建立資料庫
CREATE DATABASE test;
USE test;
DROP TABLE IF EXISTS `c_user`;
CREATE TABLE `c_user` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`phone` varchar(18) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`create_at` date NULL DEFAULT NULL,
`update_at` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
DROP TABLE IF EXISTS `c_address`;
CREATE TABLE `c_address` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`uid` int(0) NULL DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`create_at` date NULL DEFAULT NULL,
`update_at` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
3. 在pom.xml檔案中引入maven依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--<scope>runtime</scope>-->
</dependency>
4. 編寫application.properties檔案
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
spring.datasource.username=root
spring.datasource.password=123456
server.port=8081
spring.jpa.hibernate.ddl-auto=none
#是否會列印sql語句,true為列印
spring.jpa.show-sql=true
5. 配置Swagger
@Configuration
@EnableSwagger2
public class Swagger2 {
final String host = "localhost";
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.host(host)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
6. 編寫Json工具類,主要是把資料轉為json格式
public class JsonCode<T> {
public static class ResponseBean<T>{
private Integer status;
private Integer error_code;
private String error_message;
private T data;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getError_code() {
return error_code;
}
public void setError_code(Integer error_code) {
this.error_code = error_code;
}
public String getError_message() {
return error_message;
}
public void setError_message(String error_message) {
this.error_message = error_message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
public String ResponseFail(int ErrorCode, String ErrorMessage) {
ResponseBean<T> responseBean = new ResponseBean<T>();
responseBean.setError_code(ErrorCode);
responseBean.setError_message(ErrorMessage);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
return gson.toJson(responseBean);
}
public String ResponseSuccess(T data) {
ResponseBean<T> responseBean = new ResponseBean<T>();
responseBean.setData(data);
responseBean.setError_code(0);
responseBean.setError_message("");
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
return gson.toJson(responseBean);
}
public String ResponseSuccess() {
ResponseBean<T> responseBean = new ResponseBean<T>();
responseBean.setData(null);
responseBean.setError_code(0);
responseBean.setError_message("");
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
return gson.toJson(responseBean);
}
}
7. 編寫WebMvcConfig
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Bean
public PageableHandlerMethodArgumentResolverCustomizer customize() {
return p -> p.setOneIndexedParameters(true);
}
static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS)
.maxAge(3600);
}
}
8. 主啟動類編寫
@EnableJpaAuditing
@EnableSwagger2
@SpringBootApplication
@Configuration
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
9. 使用者實體類(CUserEntity)
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "c_user",schema = "",catalog = "")
public class CUserEntity {
private int id;
private String username;
private String phone;
@CreatedDate
@DateTimeFormat(pattern = "yyyy-MM-dd HH-mm-ss")
private Timestamp createAt;
@LastModifiedDate
@DateTimeFormat(pattern = "yyyy-MM-dd HH-mm-ss")
private Timestamp updateAt;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Basic
@Column(name = "phone")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Basic
@Column(name = "create_at")
public Timestamp getCreateAt() {
return createAt;
}
public void setCreateAt(Timestamp createAt) {
this.createAt = createAt;
}
@Basic
@Column(name = "update_at")
public Timestamp getUpdateAt() {
return updateAt;
}
public void setUpdateAt(Timestamp updateAt) {
this.updateAt = updateAt;
}
}
10. 位址實體類(CAddressEntity)
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "c_address")
public class CAddressEntity {
private int id;
private int uid;
private String address;
@CreatedDate
@DateTimeFormat(pattern = "yyyy-MM-dd HH-mm-ss")
private Timestamp createAt;
@LastModifiedDate
@DateTimeFormat(pattern = "yyyy-MM-dd HH-mm-ss")
private Timestamp updateAt;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "uid")
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
@Basic
@Column(name = "address")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Basic
@Column(name = "create_at")
public Timestamp getCreateAt() {
return createAt;
}
public void setCreateAt(Timestamp createAt) {
this.createAt = createAt;
}
@Basic
@Column(name = "update_at")
public Timestamp getUpdateAt() {
return updateAt;
}
public void setUpdateAt(Timestamp updateAt) {
this.updateAt = updateAt;
}
}
11. 編寫CUserEntityRepository
public interface CUserEntityRepository extends JpaRepository<CUserEntity,Integer>, JpaSpecificationExecutor<CUserEntity> {
//簡單的查詢隻需要根據JPA命名規則來命名方法,就可以直接使用了,不需要編寫SQL語句,非常友善
CUserEntity findFirstById(int id);
CUserEntity findFirstByUsername(String username);
CUserEntity findFirstByPhone(String phone);
}
12. 編寫CAddressEntityRepository
public interface CAddressEntityRepository extends JpaRepository<CAddressEntity, Integer>, JpaSpecificationExecutor<CAddressEntity> {
//複雜的查詢則需要自己編寫SQL語句
@Query(value = "SELECT c_user.username,c_user.phone,c_address.* FROM c_address LEFT JOIN c_user ON c_user.id = c_address.uid " +
"WHERE c_user.id = ?1",
nativeQuery = true)
List<Map<String,Object>> NativeFindByUserId(int id);
@Query(value = "SELECT c_user.username,c_user.phone,c_address.* FROM c_address LEFT JOIN c_user " +
"ON c_user.id = c_address.uid WHERE IF(IFNULL(?1,'') !='',c_user.id = ?1,1 = 1) AND IF(?2 != '',c_user.username = ?2,1 = 1) AND " +
"IF(?3 != '',c_user.phone = ?3,1 = 1) ",
nativeQuery = true)
Page<Map<String,Object>> NativeFindAllByUsernameOrPhone(Integer id,String username, String phone, Pageable pageable);
}
13. 編寫UserMessageWebController
@RestController
@RequestMapping("/api")
public class UserMessageWebController {
//使用者資訊
//檢視/添加/删除/修改
@Autowired
CUserEntityRepository cUserEntityRepository;
//查詢使用者資訊
@GetMapping(value = "/userMessage")
public String userMessage(HttpServletRequest request,
@RequestParam(value = "username",required = true) String username
){
CUserEntity cUserEntity = cUserEntityRepository.findFirstByUsername(username);
if(cUserEntity == null){
return new JsonCode<>().ResponseFail(99,"log_out");
}
return new JsonCode<>().ResponseSuccess(cUserEntity);
}
//添加使用者資訊
@PostMapping(value = "/userMessage")
public String addUserMessage(HttpServletRequest request,
@RequestParam(value = "username",required = true) String username,
@RequestParam(value = "phone",required = true) String phone
){
CUserEntity cUserEntity = new CUserEntity();
cUserEntity.setUsername(username);
cUserEntity.setPhone(phone);
cUserEntityRepository.saveAndFlush(cUserEntity);
return new JsonCode<>().ResponseSuccess();
}
//修改使用者資訊
@PutMapping(value = "/userMessage")
public String changeUserMessage(HttpServletRequest request,
@RequestParam(value = "username",required = true) String username,
@RequestParam(value = "phone",required = true) String phone
){
CUserEntity cUserEntity = cUserEntityRepository.findFirstByUsername(username);
if(cUserEntity == null){
return new JsonCode<>().ResponseFail(99,"log_out");
}
cUserEntity.setPhone(phone);
cUserEntityRepository.save(cUserEntity);
return new JsonCode<>().ResponseSuccess();
}
//删除使用者資訊
@DeleteMapping(value = "/userMessage")
public String deleteUserMessage(HttpServletRequest request,
@RequestParam(value = "username",required = true) String username
){
CUserEntity cUserEntity = cUserEntityRepository.findFirstByUsername(username);
if(cUserEntity == null){
return new JsonCode<>().ResponseFail(99,"log_out");
}
cUserEntityRepository.delete(cUserEntity);
return new JsonCode<>().ResponseSuccess();
}
}
14. 編寫UserAddressWebController
@RestController
@RequestMapping("/api")
public class UserAddressWebController {
@Autowired
CAddressEntityRepository cAddressEntityRepository;
@Autowired
CUserEntityRepository cUserEntityRepository;
@GetMapping(value = "/userAddress1")
public String userAddress(HttpServletRequest request,
@RequestParam(value = "username",required = true) String username
){
CUserEntity cUserEntity = cUserEntityRepository.findFirstByUsername(username);
if(cUserEntity == null){
return new JsonCode<>().ResponseFail(99,"log_out");
}
List<Map<String, Object>> address = cAddressEntityRepository.NativeFindByUserId(cUserEntity.getId());
return new JsonCode<>().ResponseSuccess(address);
}
@GetMapping(value = "/userAddress2")
public String userAddress(HttpServletRequest request,
@RequestParam(value="page", required=true) int page,
@RequestParam(value = "id",required = false) int id,
@RequestParam(value = "username",required = false) String username,
@RequestParam(value = "phone",required = false) String phone
){
Pageable firstPageWithTwoElements = PageRequest.of(page, 10);
Page<Map<String, Object>> address = cAddressEntityRepository.NativeFindAllByUsernameOrPhone(id,username,phone,firstPageWithTwoElements);
return new JsonCode<>().ResponseSuccess(address);
}
}
15. 最後測試一下
Swagger文檔的位址: http://localhost:8081/swagger-ui.html#/
測試接口位址: http://localhost:8081/api/userMessage?username=張三
16. 總結
這是一個Spring Boot + JPA + Swagger的入門項目,主要是介紹一下如何在Spring Boot中使用JPA和Swagger,如果想要更加了解JPA的使用,還是需要自己更加深入地去學習一下的。