我的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的使用,还是需要自己更加深入地去学习一下的。