导入数据后如何在数据库中分配外键列

问题描述 投票:0回答:1

我已经设置了一个测试环境来弄清楚如何将 2 个表从 excel 导入到数据库中,然后在这两个表之间创建一个关系,该关系填充两个表中的外键来表示该关系。

我可以使用邮递员导入两个表,但我似乎无法填充外键,它们按照我想要的方式出现在表中,但外键列设置为“空”。它不显示外键 ID 属性。

我正在使用数据库 H2、Spring Boot 和 Java 版本 17。我希望能够将 Excel 表导入数据库并在两个表之间进行关系映射。导入数据后我所看到的只是外键字段中的“空”。我如何让它填充?我的代码如下,我附加了制作 2 个表、服务、控制器、存储库、excel 类的实体以及我的 H2 数据库在外键列中带有“null”字段的图片:

@Entity
public class SocialProfile {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String profilename;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "SOCIAL_USER_ID", referencedColumnName = "id")
    private SocialUser user;

    public SocialProfile() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getProfilename() {
        return profilename;
    }

    public void setProfilename(String profilename) {
        this.profilename = profilename;
    }

    public SocialUser getUser() {
        return user;
    }

    public void setUser(SocialUser user) {
        this.user = user;

    }

}

@Entity
public class SocialUser {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;

    @OneToOne(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private SocialProfile socialProfile;

    public SocialUser(Long id, String username, SocialProfile socialProfile) {
        super();
        this.id = id;
        this.username = username;
        this.socialProfile = socialProfile;
    }

    public SocialUser() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public SocialProfile getSocialProfile() {
        return socialProfile;
    }

    public void setSocialProfile(SocialProfile socialProfile) {
        socialProfile.setUser(this);
        this.socialProfile = socialProfile;
    }
}


public class Excel {
    
    public static boolean isValidExcelFile(MultipartFile file) {
        return Objects.equals(file.getContentType(),
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    }

    public static List<SocialProfile> getCustomersDataFromExcel(InputStream inputStream) {
        List<SocialProfile> customers = new ArrayList<>();
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = workbook.getSheet("socialprofile");
            int rowIndex = 0;
            for (Row row : sheet) {
                if (rowIndex == 0) {
                    rowIndex++;
                    continue;
                }
                Iterator<Cell> cellIterator = row.iterator();
                int cellIndex = 0;
                SocialProfile customer = new SocialProfile();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    switch (cellIndex) {
                    case 0 -> customer.setProfilename(cell.getStringCellValue());   
                    default -> {
                    }
                    }
                    cellIndex++;
                }
                customers.add(customer);
            }
        } catch (IOException e) {
            e.getStackTrace();
        }
        return customers;
    }
    
    
    public static List<SocialUser> getUserDataFromExcel(InputStream inputStream) {
        List<SocialUser> customers = new ArrayList<>();
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = workbook.getSheet("socialuser");
            int rowIndex = 0;
            for (Row row : sheet) {
                if (rowIndex == 0) {
                    rowIndex++;
                    continue;
                }
                Iterator<Cell> cellIterator = row.iterator();
                int cellIndex = 0;
                SocialUser customer = new SocialUser();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    switch (cellIndex) {
                    case 0 -> customer.setUsername(cell.getStringCellValue());
    
                    default -> {
                    }
                    }
                    cellIndex++;
                }
                customers.add(customer);
            }
        } catch (IOException e) {
            e.getStackTrace();
        }
        return customers;
    }

}

@Repository
public interface SocialProfileRepo extends JpaRepository<SocialProfile, Integer> {

}


@Repository
public interface SocialUserRepo extends JpaRepository<SocialUser, Integer>{

}

@Service
public class SocialProfileService {

    @Autowired
    private SocialProfileRepo customerRepo;

    public void importCustomerToDatabase(MultipartFile file) {
        try {
            List<SocialProfile> custList = Excel.getCustomersDataFromExcel(file.getInputStream());
            customerRepo.saveAll(custList);
        } catch (IOException ex) {
            throw new RuntimeException("Data is not stored successfully: " + ex.getMessage());
        }

    }

}


@Service
public class SocialUserService {

    @Autowired
    private SocialUserRepo customerRepo;

    public void importUserToDatabase(MultipartFile file) {
        try {
            List<SocialUser> custList = Excel.getUserDataFromExcel(file.getInputStream());
            customerRepo.saveAll(custList);
        } catch (IOException ex) {
            throw new RuntimeException("Data is not stored successfully: " + ex.getMessage());
        }

    }

}


@RestController
public class SocialProfileController {
    
    @Autowired
    SocialProfileService customerService;

    @PostMapping("/customer/excel/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        String message = "";
        if (Excel.isValidExcelFile(file)) {
            try {
                customerService.importCustomerToDatabase(file);
                message = "The Excel file is uploaded: " + file.getOriginalFilename();
                return ResponseEntity.status(HttpStatus.OK).body(message);
            } catch (Exception exp) {
                message = "The Excel file is not uploaded: " + file.getOriginalFilename();
                return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
            }
        }
        message = "Please upload an excel file!";
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(message);
    }

}

@RestController
public class SocialUserController {

    @Autowired
    SocialUserService customerService;

    @PostMapping("/user/excel/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        String message = "";
        if (Excel.isValidExcelFile(file)) {
            try {
                customerService.importUserToDatabase(file);
                message = "The Excel file is uploaded: " + file.getOriginalFilename();
                return ResponseEntity.status(HttpStatus.OK).body(message);
            } catch (Exception exp) {
                message = "The Excel file is not uploaded: " + file.getOriginalFilename();
                return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
            }
        }
        message = "Please upload an excel file!";
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(message);
    }
}


H2图像

更新: 感谢您的反馈。我在控制器中添加了以下代码,这似乎完成了这个技巧,但也产生了另一个问题。我现在正在填充外键字段,但我正在获取在每个其他字段中创建为空的导入行的确切数量。请参阅下面我添加到控制器中的代码:

@Service

公共课社会服务{

@Autowired
SocialUserRepo socialUserRepo;

@Autowired
SocialProfileRepo socialProfileRepo;

public void importUserToDatabase(MultipartFile file) {
    try {
        List<SocialUser> custList = Excel.getUserDataFromExcel(file.getInputStream());

        for (SocialUser user : custList) {
            SocialProfile scProfile = new SocialProfile();
            user.setSocialProfile(scProfile);
        }

        socialUserRepo.saveAll(custList);
    } catch (IOException ex) {
        throw new RuntimeException("Data is not stored successfully: " + ex.getMessage());
    }

}

public void importCustomerToDatabase(MultipartFile file) {
    try {
        List<SocialProfile> custList = Excel.getCustomersDataFromExcel(file.getInputStream());

        for (SocialProfile profile : custList) {
            SocialUser scUser = new SocialUser();
            profile.setSocialUser(scUser);
        }

        socialProfileRepo.saveAll(custList);

    } catch (IOException ex) {
        throw new RuntimeException("Data is not stored successfully: " + ex.getMessage());
    }

}

H2 数据库中重复空行

java spring spring-boot jpa
1个回答
0
投票

现在已经解决了。

我修改了 Excel 类的读取逻辑以包含关系信息:

ent
© www.soinside.com 2019 - 2024. All rights reserved.