Spring Boot JPA调用RestAPI获取嵌套JSON存储至多关联表的方案咨询
实现方案
前置修正:实体类注解问题
你当前的ApplicationUserRoleMap实体关联注解配置错误,该表是应用、用户、角色三者的关联映射表,单条记录仅对应唯一的应用、用户、角色组合,需将原有@ManyToMany改为@ManyToOne:
@ManyToOne @JoinColumn(name="APPLICATION_ID") private Application application; @ManyToOne @JoinColumn(name="USER_ID") private User user; @ManyToOne @JoinColumn(name="ROLE_ID") private Role role;
对应的三个主实体里的List<ApplicationUserRoleMap>关联注解调整为@OneToMany(mappedBy = "对应属性名")即可。
步骤1:定义接口响应DTO
新增DTO类匹配第三方接口返回的JSON结构,无需和数据库实体绑定:
@Data public class ApiAppDTO { @JsonProperty("ApplicationName") private String applicationName; @JsonProperty("city") private String city; @JsonProperty("IsActive") private String isActive; @JsonProperty("AppOwner") private String appOwner; @JsonProperty("AppTeamMember") private String appTeamMember; @JsonProperty("CreatedBy") private String createdBy; @JsonProperty("AppDetails") private AppDetailsDTO appDetails; @Data public static class AppDetailsDTO { @JsonProperty("Language") private String language; @JsonProperty("Version") private String version; } }
步骤2:调用第三方GET接口
Spring Boot中推荐新手用RestTemplate实现接口调用,先注册Bean:
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
调用示例:
@Autowired private RestTemplate restTemplate; // 调用接口获取响应 List<ApiAppDTO> response = restTemplate.exchange( "你的第三方接口URL", HttpMethod.GET, null, new ParameterizedTypeReference<List<ApiAppDTO>>() {} ).getBody();
步骤3:编写JPA Repository接口
为每个实体类创建对应的Repository,继承JpaRepository实现数据库操作:
// ApplicationRepository public interface ApplicationRepository extends JpaRepository<Application, Long> { Optional<Application> findByApplicationName(String applicationName); } // UserRepository public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByUserName(String userName); } // RoleRepository public interface RoleRepository extends JpaRepository<Role, Long> { Optional<Role> findByRoleName(String roleName); } // ApplicationUserRoleMapRepository public interface ApplicationUserRoleMapRepository extends JpaRepository<ApplicationUserRoleMap, Long> { }
步骤4:核心业务逻辑实现
在Service层编写处理逻辑,添加@Transactional事务控制保证数据一致性,逻辑包含去重判断避免重复插入相同用户、角色、应用数据:
@Service @Transactional(rollbackFor = Exception.class) public class AppSyncService { @Autowired private ApplicationRepository applicationRepo; @Autowired private UserRepository userRepo; @Autowired private RoleRepository roleRepo; @Autowired private ApplicationUserRoleMapRepository mapRepo; public void syncAppData(List<ApiAppDTO> apiAppList) { // 遍历接口返回的每个应用数据 for (ApiAppDTO appDTO : apiAppList) { // 1. 保存/查询应用信息 Application application = applicationRepo.findByApplicationName(appDTO.getApplicationName()) .orElseGet(() -> { Application newApp = new Application(); newApp.setApplicationName(appDTO.getApplicationName()); newApp.setCreatedBy(appDTO.getCreatedBy()); // 其他公共字段可根据业务填充,或用JPA审计自动填充 newApp.setDeleteFlg("0"); newApp.setDisplayFlg("1"); return applicationRepo.save(newApp); }); // 2. 处理AppOwner角色和对应用户 saveRoleUserMap(application, "AppOwner", appDTO.getAppOwner(), appDTO.getCreatedBy()); // 3. 处理AppTeamMember角色和对应用户 saveRoleUserMap(application, "AppTeamMember", appDTO.getAppTeamMember(), appDTO.getCreatedBy()); } } // 抽取公共方法保存角色、用户、关联映射 private void saveRoleUserMap(Application application, String roleName, String userName, String operator) { // 保存/查询角色 Role role = roleRepo.findByRoleName(roleName) .orElseGet(() -> { Role newRole = new Role(); newRole.setRoleName(roleName); newRole.setCreatedBy(operator); newRole.setDeleteFlg("0"); newRole.setDisplayFlg("1"); return roleRepo.save(newRole); }); // 保存/查询用户 User user = userRepo.findByUserName(userName) .orElseGet(() -> { User newUser = new User(); newUser.setUserName(userName); newUser.setCreatedBy(operator); newUser.setDeleteFlg("0"); newUser.setDisplayFlg("1"); return userRepo.save(newUser); }); // 保存三者关联映射 ApplicationUserRoleMap map = new ApplicationUserRoleMap(); map.setApplication(application); map.setRole(role); map.setUser(user); map.setCreatedBy(operator); map.setDeleteFlg("0"); map.setDisplayFlg("1"); mapRepo.save(map); } }
优化建议
- 可在数据库
USER表的USER_NAME字段、ROLE表的ROLE_NAME字段、APPLICATION表的APPLICATION_NAME字段添加唯一索引,避免重复数据 - 公共字段
CREATED_ON、MODIFIED_ON等可使用Spring Data JPA审计功能自动填充,无需手动赋值 - 若同步数据量较大,可调整为批量插入优化性能
内容的提问来源于stack exchange,提问作者Sri
相关产品推荐
相关产品推荐

