SpringCloud+JPA实现增删查改(附源码)
引言:
本文主要分享了SpringCloud微服务的环境下使用JPA实现增删查改,用到了Eureka、feign、zuul还有JPA的相关知识;主要实现了JPA创建数据库,实现增删查改,模拟服务网关进行拦截;
文章目录
1. 目录结构总览
1.1 eurekaserver
1.2 producer_jpa
1.3 consumer_feign
1.4 Zuul
2. 创建Eurekaserver
创建SpringBoot项目(springcloud_eurekaserver),只导入EurekaServer;
- 在启动文件中加入@EnableEurekaServer注解用于开启Eureka服务注册功能
2.1 配置application.yml
server:
port: 8761
eureka:
instance:
hostname: 127.0.0.1
client:
service-url:
defaultZone: http://localhost:8761/eureka/
register-with-eureka: false
fetch-registry: false
3. 创建producer_jpa
创建SpringBoot项目(springcloud_producer_jpa),选择以下依赖;
- 在启动文件中加入@EnableEurekaClient用于启动Eureka客户端注册功能
3.1 配置application.yml
server:
port: 9091
spring:
application:
name: producer-service-jpa
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db0711?serverTimezone=UTC
username: root
password: root
jpa:
hibernate:
#ddl-auto: create
ddl-auto: update
show-sql: true
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
3.2 Student实体类
创建Student.java,完成创建表、设置自增、设置数据库字段等等;
- 在导Id的包时应导入:import javax.persistence.*;
- 注意使用@Entity声明为实体类
/**
* Created by Kak on 2020/9/25.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity //声明为实体类
@Table(name = "TB_STUDENT")
public class Student implements Serializable{
@Id
//创建自增
@GeneratedValue(strategy = GenerationType.IDENTITY)
//数据库字段
@Column(name = "ss_id")
private Integer ssId;
@Column(name = "ss_name")
private String ssname;
//默认数据库字段与该字段一致
private String sex;
private String age;
}
3.3 创建StudentRepository
/**
* dao接口
* Repository 顶级接口 空
* CrudRepository 派生 默认实现了CRUD
* PagingAndSortingRepository 继续派生 增加了分页和排序功能
* JpaRepository 继续派生 增加了批量处理功能
* Created by Kak on 2020/9/25.
*/
@Repository
public interface StudentRepository extends JpaRepository<Student,Integer>{
}
3.4 server层的实现
3.4.1 StudentService接口
/**
* Created by Kak on 2020/9/25.
*/
public interface StudentService {
/**
* 查询全部学生信息
* @return 学生信息
*/
public List<Student> findAllStudent();
/**
* 通过id查询学生信息
* @param sid 传入的id
* @return 学生对象
*/
public Student findStuById(Integer sid);
/**
* 添加记录到数据表
* @param student 无主键
* @return student 有主键
*/
public Student addStudent(Student student);
/**
*
* @param student 修改的对象信息(必须有主键)
* @return student对象 返回指定修改主键的对象所有信息
*/
public Student updateStudent(Student student);
/**
* 删除学生信息
* @param sid 传入的id
* @return 是否删除成功
*/
public boolean deleteStudentById(Integer sid);
}
3.4.2 StudentServiceImpl实现类
@Resource 注解注入:默认先按照类型搜索
- 如设置了type属性,只按照type搜索,搜不到抛异常
- 设置name属性,只按照name搜索,搜不到,抛异常
@Autowried 默认按照类型搜索,搜不到抛null
- 按照名称搜索与@Qualifer配合
/**
* Created by Kak on 2020/9/25.
*/
@Service
@Slf4j
public class StudentServiceImpl implements StudentService{
@Resource
private StudentRepository studentRepository;
@Override
public List<Student> findAllStudent() {
List<Student> all = studentRepository.findAll();
return all;
}
@Override
public Student findStuById(Integer sid) {
Optional<Student> byId = studentRepository.findById(sid);
return byId.get();
}
@Override
public Student addStudent(Student student) {
Student save = studentRepository.save(student);
return save;
}
@Override
public Student updateStudent(Student student) {
Student student1 = studentRepository.saveAndFlush(student);
return student1;
}
@Override
public boolean deleteStudentById(Integer sid) {
try{
studentRepository.deleteById(sid);
return true;
}catch (Exception ex){
log.info(ex.getMessage());
}
return false;
}
}
3.5 StudentController的实现
用于提供服务信息
/**
* Created by Kak on 2020/9/25.
*/
@RestController
public class StudentController {
@Autowired(required = false)
private StudentService studentService;
@RequestMapping(value = "/students",method = RequestMethod.GET)
public List<Student> findAll(){
List<Student> allStudent = studentService.findAllStudent();
return allStudent;
}
@RequestMapping(value = "/student/{id}",method = RequestMethod.GET)
public Student findOneStudent(@PathVariable(value = "id") int sid){
Student stuById = studentService.findStuById(sid);
return stuById;
}
@RequestMapping(value = "/student",method = RequestMethod.POST)
public Student addStudent(@RequestBody Student student){
Student student1 = studentService.addStudent(student);
return student1;
}
@RequestMapping(value = "/student",method = RequestMethod.PUT)
public Student updateStudent(@RequestBody Student student){
Student student1 = studentService.updateStudent(student);
return student1;
}
@RequestMapping(value = "/student/{id}",method = RequestMethod.DELETE)
public Boolean deleteStudent(@PathVariable(value = "id") int sid){
boolean b = studentService.deleteStudentById(sid);
return b;
}
}
4. 创建consumer_feign
创建SpringBoot项目(springcloud_consumer_feign),选择以下依赖;(数据源可以不加)
4.1 修改SpringcloudConsumerFeignApplication启动文件
在启动文件中加入:
- @EnableEurekaClient用于启动Eureka客户端注册功能;
- @EnableFeignClients用于开启feign客户端
4.2 配置application.yml
server:
port: 9093
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
spring:
application:
name: feign-client
4.3 Student实体类的实现
/**
* Created by Kak on 2020/9/25.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Serializable{
private Integer ssId;
private String ssname;
private String sex;
private String age;
}
4.4 ActionResult的实现
/**
* Created by Kak on 2020/9/25.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ActionResult {
private Integer statueCode;
private String msg;
private Object data;
}
4.5 编写RemoteFeignServer接口
/**
* Created by Kak on 2020/9/25.
*/
@FeignClient(value = "producer-service-jpa")
public interface RemoteFeignService {
@RequestMapping(value = "/students",method = RequestMethod.GET)
public List<Object> findStudent();
@RequestMapping(value = "/student/{id}",method = RequestMethod.GET)
public Student findOneStudent(@PathVariable(value = "id") int sid);
@RequestMapping(value = "/student",method = RequestMethod.POST)
public Student addStudent(@RequestBody Student student);
@RequestMapping(value = "/student",method = RequestMethod.PUT)
public Student updateStudent(@RequestBody Student student);
@RequestMapping(value = "/student/{id}",method = RequestMethod.DELETE)
public Boolean deleteStudent(@PathVariable(value = "id") int sid);
}
4.6 StuController的实现
全部使用了get请求,可以分别使用,用postman测试;
/**
* Created by Kak on 2020/9/25.
*/
@RestController
public class StudentController {
@Autowired(required = false)
private RemoteFeignService remoteFeignService;
@RequestMapping("/students")
public ActionResult findAllStu() {
List<Object> student = remoteFeignService.findStudent();
ActionResult actionResult = new ActionResult(200, "find all success", student);
return actionResult;
}
@RequestMapping("/student/{id}")
public ActionResult findOneStu(@PathVariable(value = "id") int sid){
Student oneStudent = remoteFeignService.findOneStudent(sid);
ActionResult actionResult = new ActionResult(200, "find one success", oneStudent);
return actionResult;
}
@RequestMapping("/addstudent")
public ActionResult addStu(Student student){
Student student1 = remoteFeignService.addStudent(student);
ActionResult actionResult = new ActionResult(200, "add student success", student1);
return actionResult;
}
@RequestMapping("/updateStudent")
public ActionResult updateStu(Student student){
Student student1 = remoteFeignService.updateStudent(student);
ActionResult actionResult = new ActionResult(200, "update student success", student1);
return actionResult;
}
@RequestMapping("/deleteStudent/{id}")
public ActionResult deleteStu(@PathVariable(value = "id")Integer sid){
Boolean aBoolean = remoteFeignService.deleteStudent(sid);
ActionResult actionResult = new ActionResult(200, "delete student success", aBoolean);
return actionResult;
}
}
5. 创建zuul
创建SpringBoot项目(springcloud_zuul),选择以下依赖;
5.1 修改启动文件
在启动文件中加入以下注解:
- @EnableDiscoveryClient:用于启动Eureka客户端注册功能
- @EnableZuulProxy:用于开启zuul路由代理服务
5.2 配置application.yml
server:
port: 9098
spring:
application:
name: consumer-server-zuul
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
#自定义路由
zuul:
routes:
stu:
path: /stu/**
serviceId: feign-client
5.3 配置AuthenFilter
设置过滤文件,模拟token当token=200时可以访问,否则拦截;
/**
* Created by Kak on 2020/9/25.
*/
@Component
public class AuthenFilter extends ZuulFilter {
//定义过滤器的类型
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
//定义过滤器的执行顺序。数字越小,优先执行默认5
@Override
public int filterOrder() {
return FilterConstants.PRE_DECORATION_FILTER_ORDER - 2;
}
//设定过滤器是否生效 true生效
@Override
public boolean shouldFilter() {
return true;
}
//过滤器的逻辑
@Override
public Object run() throws ZuulException {
RequestContext currentContext = RequestContext.getCurrentContext();
HttpServletRequest request = currentContext.getRequest();
//从参数中获取token
String token = request.getParameter("token");
//从请求头部获取认证令牌信息
request.getHeader("Authentication");
//令牌无效或不合法
if (token == null || !"200".equalsIgnoreCase(token)) {
currentContext.setSendZuulResponse(false);//阻止请求继续发送到微服务
currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
currentContext.setResponseBody("no permission......");
}
return null;
}
}
6. 结果展示
转载:https://blog.csdn.net/weixin_42601136/article/details/108806542
查看评论