Как назначить столбец внешнего ключа в моей базе данных после импорта данныхJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Как назначить столбец внешнего ключа в моей базе данных после импорта данных

Сообщение Anonymous »

Я настроил тестовую среду, чтобы понять, как импортировать две таблицы из Excel в базу данных, а затем создать связь между двумя таблицами, которые заполняют внешние ключи в обеих таблицах для представления этой связи.Я могу импортировать обе таблицы с помощью почтальона, но мне не удается заполнить внешние ключи, они отображаются в таблицах так, как я хочу, но столбец внешнего ключа имеет значение «ноль». Он не отображает свойства идентификатора внешнего ключа.
Я использую базу данных H2, использую Spring Boot и Java версии 17. Я хочу иметь возможность импортировать таблицы Excel в базу данных и иметь сопоставление отношений между двумя таблицами. Все, что я вижу после импорта данных, имеет значение «null» в поле внешнего ключа. Как мне заставить это заполниться? Мой код приведен ниже, я прикрепил объекты, которые составляют две таблицы, службы, контроллеры, репозитории, класс 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 getCustomersDataFromExcel(InputStream inputStream) {
List 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 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 getUserDataFromExcel(InputStream inputStream) {
List 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  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 {

}

@Repository
public interface SocialUserRepo extends JpaRepository{

}

@Service
public class SocialProfileService {

@Autowired
private SocialProfileRepo customerRepo;

public void importCustomerToDatabase(MultipartFile file) {
try {
List 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 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 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 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

Подробнее здесь: https://stackoverflow.com/questions/793 ... g-the-data
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»