@Entity
@Table(name = "pkss")
public class PKS {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
private TypeChoices partnershipType;
private LocalDateTime submissionDate = LocalDateTime.now();
@Enumerated(EnumType.STRING)
private BudgetTypeChoices budgetType;
private String budgetNumber;
@Enumerated(EnumType.STRING)
private MethodeTypeChoices partnershipMethod;
@Enumerated(EnumType.STRING)
private MaterialTypeChoices materialType;
private String title;
private String background;
private String note;
private String partnershipCandidate;
@ManyToOne
private User user;
@Enumerated(EnumType.STRING)
private StatusChoices status;
private int positionLevel = 1;
private boolean isStopClock = false;
private String responseText;
private String approvalNote;
private String pksNumber;
private LocalDateTime approvalCompletionDate;
@ManyToOne
private Functionary officialUndersign;
}
я могу вам сказать следующее:
- PKS — привязанность: один ко многим
- PKS – RAB: один ко многим
- PKS – Область применения: один ко многим
- PKS – официальная подпись: многие к одному< /li>
@Entity
@Table(name = "attachments")
public class Attachment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String filename;
private String filePath;
@ManyToOne(optional = true)
@JoinColumn(name = "mou_nda_id", nullable = true)
private MouNda mouNda;
@ManyToOne(optional = true)
@JoinColumn(name = "pks_id", nullable = true)
private PKS pks;
public class AttachmentDTO {
private String file;
// Getters and Setters
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public String getFilePath(String typeDir) {
return "/home/bintang/media/attachments/" + typeDir + this.file;
}
}
а ниже — pksdto
public class PKSDTO {
private Long id;
private String base; // Assuming you have a similar enum or String for 'base'
private LocalDateTime submissionDate; // DateTime field for submission date
private String partnershipTitle; // Title for the partnership
private String background; // Background information
private String note; // Notes
private String partnershipCandidate; // Candidate for the partnership
private String status; // Status of the PKS
private int positionLevel; // Position level
private boolean isStopClock; // Stop clock flag
private String responseText; // Response text
private String approvalNote; // Approval note
private String pksNumber; // PKS number
private LocalDateTime approvalCompletionDate; // Approval completion date
private Long userId; // ID of the user
private Long officialUndersign; // ID of the official undersign
private List rab; // List of RAB
private List scopesPks; // List of scopes
private List attachmentsPks; // List of attachments
}
и это есть в сервисе
public ResponseEntity createPks(PKSDTO pksDto) throws IOException {
// Check if userId is provided
if (pksDto.getUserId() == null) {
throw new IllegalArgumentException("User ID must not be null");
}
// Find user
User user = userRepository.findById(pksDto.getUserId())
.orElseThrow(() -> new RuntimeException("User tidak ditemukan"));
// Create and set up the PKS object
PKS pks = new PKS();
pks.setUser(user);
pks.setTitle(pksDto.getPartnershipTitle());
pks.setBackground(pksDto.getBackground());
pks.setNote(pksDto.getNote());
pks.setStatus(StatusChoices.valueOf(pksDto.getStatus()));
pks.setSubmissionDate(pksDto.getSubmissionDate());
pks.setPositionLevel(pksDto.getPositionLevel());
pks.setResponseText(pksDto.getResponseText());
pks.setApprovalNote(pksDto.getApprovalNote());
pks.setPksNumber(pksDto.getPksNumber());
pks.setApprovalCompletionDate(pksDto.getApprovalCompletionDate());
// Save the PKS object to the database
pks = pksRepository.save(pks);
// Save scopes if present
if (pksDto.getScopesPks() != null) {
for (ScopeDTO scopeDto : pksDto.getScopesPks()) {
Scope scope = new Scope();
scope.setScopeName(scopeDto.getScopeName());
scope.setPks(pks);
scopeRepository.save(scope);
}
}
// Save RAB if present
if (pksDto.getRab() != null) {
for (RabDTO rabDto : pksDto.getRab()) {
RAB rab = new RAB();
rab.setCustomer(rabDto.getCustomer());
rab.setType(TypeChoices.valueOf(rabDto.getType()));
rab.setRevenue(rabDto.getRevenue());
rab.setCost(rabDto.getCost());
rab.setCostDesc(rabDto.getCostDesc());
rab.setPks(pks);
rabRepository.save(rab);
}
}
// Save attachments if present
if (pksDto.getAttachmentsPks() != null) {
for (AttachmentDTO file : pksDto.getAttachmentsPks()) {
String fileName = FileNameUtils.generateSafeFileName(file.getFile());
String filePath = baseDir + fileName;
// Save the file to the file system
// SaveFile.save(file, filePath); // You may need to implement SaveFile.save() method
// Create and save the attachment object
Attachment attachment = new Attachment();
attachment.setFilePath(filePath);
attachment.setFilename(fileName);
attachment.setPks(pks);
attachmentRepository.save(attachment);
}
}
return new ResponseEntity(pks, HttpStatus.CREATED);
}
мой вопрос:
- как создать контроллер с помощью @PostMapping и несколько вложений файл в теле? Мои ссылки взяты из сериализатора django ниже.
- как мне сохранить в файловой системе и сохранить путь в базе данных?
from rest_framework import serializers
from api.models import *
class ScopeSerializer(serializers.ModelSerializer):
class Meta:
model = Scope
fields = ['scope_name']
class AttachmentSerializer(serializers.ModelSerializer):
class Meta:
model = Attachment
fields = ['file']
class RabSerializer(serializers.ModelSerializer):
class Meta:
model = RAB
fields = '__all__'
class MouNdaSerializer(serializers.ModelSerializer):
scopes_mou = ScopeSerializer(many=True, required=False)
attachments_mou = AttachmentSerializer(many=True, required=False)
class Meta:
model = Mou_Nda
fields = '__all__'
class PKSSerializer(serializers.ModelSerializer):
rab = RabSerializer(many=True, required=False)
scopes_pks = ScopeSerializer(many=True, required=False)
attachments_pks = AttachmentSerializer(many=True, required=False)
class Meta:
model = PKS
fields = '__all__'
Подробнее здесь: https://stackoverflow.com/questions/791 ... n-rest-api
Мобильная версия