@Entity
public class Ad {
@Id
@SequenceGenerator(name = "clientsIdSeq5", sequenceName = "users_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "clientsIdSeq5")
private Long id;
private String label;
// @Lob
@Column(columnDefinition = "TEXT")
private String body;
private boolean is_views;
private LocalDateTime update_time;
private LocalDateTime created_at;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "subcategory_id")
private Subcategory subcategoryId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "stations_id")
private MetroStations stationsId;
@ManyToOne
@JoinColumn(name = "user_id")
private User author;
@OneToMany(mappedBy = "ad", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<AdImages> images;
@Entity
public class AdImages {
@Id
@SequenceGenerator(name = "clientsIdSeq5", sequenceName = "ad_images_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "clientsIdSeq5")
private Long id;
@ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
private Ad ad;
private String fileName;
public String addAd(
@AuthenticationPrincipal User user,
@RequestParam Long subcategory,
@RequestParam String label,
@RequestParam String body,
@RequestParam Long subwayStation,
@RequestParam("files") MultipartFile[] files,
Map<String, Object> model) throws IOException {
LocalDateTime dateTimeNow = LocalDateTime.now();
Optional<Subcategory> subcategoryItem = subcategoryRepo.findById(subcategory);
Optional<MetroStations> metroStations = metroStationsRepo.findById(subwayStation);
Ad ad = new Ad(label, body, true, dateTimeNow, dateTimeNow, subcategoryItem, metroStations, user);
if (files != null){
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()){
uploadDir.mkdir();
}
List<String> fileNames = null;
for (MultipartFile file: files) {
String uuidFile = UUID.randomUUID().toString();
String resultFileName = uuidFile + "." + file.getOriginalFilename();
file.transferTo(new File(resultFileName));
fileNames.add(resultFileName);
}
// ad.setImages(fileNames);
}
adRepo.save(ad);
final List<AdImage> imageList = new ArrayList<>();
for (...) {
...
final AdImage image = new AdImage(...); //Аналогично тому как вы создаете Ad
imageList.add(image);
...
}
ad.setImages(imageList);
Еще вопрос можно ли в в AdImages избавить от колонки id?