我们使用上一章节的项目环境进行开发。
https://blog.51cto.com/u_13312531/6536187
一、父项目引入SpringBoot
我们在父项目pom文件中统一管理引入的jar包的版本。我们采用父项目中以depencyMangement方式引入spring-boot,子项目依赖parent父配置即可。
<?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>
<groupId>org.example</groupId>
<artifactId>mymall</artifactId>
<version>1.0-SNAPSHOT</version>
<!--设置为pom,管理依赖-->
<packaging>pom</packaging>
<modules>
<module>mymall-common</module>
<module>mymall-goods</module>
<module>mymall-order</module>
<module>mymall-pay</module>
<module>mymall-stock</module>
<module>mymall-user</module>
</modules>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!--统一管理项目依赖版本-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
二、common模块的开发
pom文件如下:
<?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.example</groupId>
<artifactId>myshop</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>myshop-common</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--hibernate-validate-->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
<!--JPA-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
</project>
在父项目目录下创建application.yml配置文件,管理整个项目统一的配置。
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/mymall?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false&rewriteBatchedStatements=true
username: root
password: 123456
jpa:
hibernate:
ddl-auto: update
show-sql: true
修改后的项目结构如下:
我们在common模块中创建一个统一结果返回实体类CommonResult。
示例代码如下:
package com.example.mymall.common;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author qx
* @date 2023/06/23
* @desc 统一结果返回实体
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult implements Serializable {
private Integer code;
private String message;
private Object data;
public static CommonResult success() {
return CommonResult.builder().code(200).message("请求成功").build();
}
public static CommonResult success(Object data) {
return CommonResult.builder().code(200).message("请求成功").data(data).build();
}
public static CommonResult fail(String message) {
return CommonResult.builder().code(500).message(message).build();
}
}
使用JPA创建一个用户实体类
package com.example.mymall.entity;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.Date;
/**
* @author qx
* @date 2023/06/23
* @desc
*/
@Entity
@Table(name = "t_user")
@Data
@DynamicUpdate
@DynamicInsert
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 用户名
*/
@NotBlank(message = "用户名不能为空")
private String userName;
/**
* 用户性别:0:女 1:男 2:未知
*/
private Integer sex;
/**
* 手机号
*/
@NotBlank(message = "手机号不能为空")
private String phone;
/**
* 邮箱
*/
private String email;
/**
* 地址
*/
private String address;
/**
* 积分
*/
@Column(columnDefinition = "int default 0 comment '积分'")
private Integer integral;
/**
* 等级
*/
@Column(columnDefinition = "int default 1 comment '等级'")
private Integer level;
/**
* 创建时间
*/
@CreationTimestamp
private Date createTime;
/**
* 修改时间
*/
@UpdateTimestamp
private Date updateTime;
/**
* 状态 1:正常 2:禁用
*/
@Column(columnDefinition = "int default 1 comment '状态'")
private Integer status;
}
三、user模块的开发
1.pom文件中引入common模块的依赖
<?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.example</groupId>
<artifactId>mymall</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>mymall-user</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>mymall-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
2.创建数据访问层
package com.example.mymall.repository;
import com.example.mymall.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
3.创建用户服务层
package com.example.mymall.service;
import com.example.mymall.entity.User;
import com.example.mymall.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author qx
* @date 2023/06/23
* @desc 用户服务层
*/
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void saveUser(User user) {
userRepository.save(user);
}
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
}
4.创建用户控制层
package com.example.mymall.controller;
import com.example.mymall.common.CommonResult;
import com.example.mymall.entity.User;
import com.example.mymall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* @author qx
* @date 2023/06/23
* @desc 用户控制层
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 添加用户
*/
@PostMapping("/add")
public CommonResult addUser(@Validated @RequestBody User user) {
userService.saveUser(user);
return CommonResult.success();
}
/**
* 根据id获取用户信息
*
* @param id 用户ID
* @return 用户信息
*/
@GetMapping("/{id}")
public CommonResult getUserById(@PathVariable("id") Long id) {
return CommonResult.success(userService.getUserById(id));
}
}
5.创建用户模块启动类
package com.example.mymall;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author qx
* @date 2023/06/23
* @desc 用户模块启动类
*/
@SpringBootApplication
public class MyMallUserApplication {
public static void main(String[] args) {
SpringApplication.run(MyMallUserApplication.class, args);
}
}
运行启动类,由于我们使用JPA机制自动创建了数据表
2023-06-23 23:08:14.997 INFO 9028 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Hibernate: create table t_user (id bigint not null auto_increment, address varchar(255), create_time datetime(6), email varchar(255), integral int default 0 comment '积分', level int default 1 comment '等级', phone varchar(255), sex integer, status int default 1 comment '状态', update_time datetime(6), user_name varchar(255), primary key (id)) engine=InnoDB
2023-06-23 23:08:17.727 INFO 9028 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2023-06-23 23:08:17.736 INFO 9028 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2023-06-23 23:08:18.104 WARN 9028 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2023-06-23 23:08:18.240 INFO 9028 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2023-06-23 23:08:18.449 INFO 9028 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2023-06-23 23:08:18.451 INFO 9028 --- [ main] c.example.mymall.MyMallUserApplication : Started MyMallUserApplication in 6.21 seconds (JVM running for 7.61)
6.测试
我们使用Postman进行接口的测试,首先测试用户新增接口
我们刷新数据表,发现数据成功添加到了数据表中。
继续测试用户查询接口
到这里我们基本完成了公共模块和用户子模块的基本开发,其他功能可以自己去实现。
标签:23,SpringCloud,mymall,private,Alibaba,模块,org,import,example From: https://blog.51cto.com/u_13312531/6539601