Добавлены связь - многие ко многим, есть баг с галочками))

This commit is contained in:
ArtemEmelyanov 2023-05-12 21:23:55 +04:00
parent 66052b7078
commit e54c2dc46e
9 changed files with 169 additions and 9 deletions

Binary file not shown.

View File

@ -2,5 +2,6 @@ export default class Subject{
constructor(data) { constructor(data) {
this.id = data?.id; this.id = data?.id;
this.name = data?.name; this.name = data?.name;
this.groupIds = data?.groupIds;
} }
} }

View File

@ -19,11 +19,15 @@
<td> <td>
<button class="btn btn-danger" @click="deleteSubject(sbjct.id)">Удалить</button> <button class="btn btn-danger" @click="deleteSubject(sbjct.id)">Удалить</button>
</td> </td>
<td>
<button class="btn btn-primary mr-2" @click="openModalForAdd('edit',sbjct);">Добавить предметы в группы</button>
</td>
</td> </td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
</div> </div>
<!--Форма для создания и добавления предметов-->
<div class="modal" tabindex="-1" id="editModal"> <div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog"> <div class="modal-dialog">
<div class="modal-content"> <div class="modal-content">
@ -46,6 +50,39 @@
</div> </div>
</div> </div>
</div> </div>
<!--Форма для привязки предмета и групп -->
<div class="modal" tabindex="-1" id="openModalForAdd">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Добавление групп</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="name">Имя:</label>
<input readonly type="text" class="form-control" id="name" name="name" v-model="subject.name">
</div>
<div class="form-group">
<label for="name">Выберите группы для добавления:</label>
<ul class="list-group">
<li class="list-group-item" v-for="group in groups" :key="group.id">
<div class="form-check">
<input class="form-check-input" type="checkbox" v-model="selectedGroups" :value="group.id" :checked="open.includes(group.id)" id="groupCheck{{ group.id }}">
<label class="form-check-label" for="groupCheck{{ group.id }}">{{ group.name }}</label>
</div>
</li>
</ul>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModalForAdd()">Закрыть</button>
<button type="button" class="btn btn-primary" @click="addSubjectToGroup(subject.id, selectedGroups)">Добавить</button>
</div>
</div>
</div>
</div>
</template> </template>
<script> <script>
import 'axios'; import 'axios';
@ -55,11 +92,16 @@ import Group from "@/models/Group";
export default { export default {
created() { created() {
this.getSubjects(); this.getSubjects();
this.getGroups();
this.getAllSubjectGroup();
}, },
mounted() { mounted() {
const addModal = document.getElementById('editModal'); const addModal = document.getElementById('editModal');
addModal.addEventListener('shown.bs.modal', function () { addModal.addEventListener('shown.bs.modal', function () {
}) })
const openModalForAdd = document.getElementById('openModalForAdd');
openModalForAdd.addEventListener('shown.bs.modal', function () {
})
}, },
data() { data() {
@ -67,21 +109,33 @@ export default {
subjects: [], subjects: [],
URL: "http://localhost:8080/", URL: "http://localhost:8080/",
subject: new Subject(), subject: new Subject(),
groups: [],
selectedGroups: [],
AllSubjectGroup: [],
open: [],
} }
}, },
methods: { methods: {
getSubjects(){ getAllSubjectGroup(){
axios.get(this.URL + "subject") axios.get(this.URL + "subject/getAllSubjectGroup")
.then(response => { .then(response => {
this.subjects = response.data; this.AllSubjectGroup = response.data;
console.log(response.data); console.log(response.data);
}) })
.catch(error => { .catch(error => {
console.log(error); console.log(error);
}); });
}, },
getSubjects(){
axios.get(this.URL + "subject")
.then(response => {
this.subjects = response.data;
})
.catch(error => {
console.log(error);
});
},
addSubject(subject){ addSubject(subject){
console.log(this.subjects);
axios.post(this.URL + "subject", subject) axios.post(this.URL + "subject", subject)
.then(() => { .then(() => {
this.getSubjects(); this.getSubjects();
@ -109,9 +163,27 @@ export default {
}) })
this.closeModal(); this.closeModal();
}, },
openModalForAdd(status, subject = null){
this.open = [];
console.log("Открылось" + this.open);
if (status === "create") {
this.subject = new Subject();
this.subject.status = "create";
} else if (status === "edit" && subject) {
this.subject = { ...subject };
this.subject.status = "edit";
this.open = this.subject.groupIds; // Инициализация groupIds из subject
}
document.getElementById("openModalForAdd").style.display = "block";
},
closeModalForAdd(){
document.getElementById("openModalForAdd").style.display = "none";
this.open = [];
console.log("Закрылось" + this.open);
},
openModal(status, subject = null) { openModal(status, subject = null) {
if (status === "create") { if (status === "create") {
this.subject = new Group(); this.subject = new Subject();
this.subject.status = "create"; this.subject.status = "create";
} else if (status === "edit" && subject) { } else if (status === "edit" && subject) {
this.subject = { ...subject }; this.subject = { ...subject };
@ -122,6 +194,27 @@ export default {
closeModal() { closeModal() {
document.getElementById("editModal").style.display = "none"; document.getElementById("editModal").style.display = "none";
}, },
getGroups(){
axios.get(this.URL + "group")
.then(response => {
this.groups = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
addSubjectToGroup(id, list){
this.open = [];
console.log("Добавилось" + this.open);
axios.post(this.URL + `subject/${id}/addSubjectToGroup`, list)
.then(()=>{
this.closeModalForAdd();
})
.catch(error => {
console.log(error);
});
},
} }
} }
</script> </script>

View File

@ -2,16 +2,20 @@ package ru.IP_LabWorks.IP.University.Contoller.DTO;
import ru.IP_LabWorks.IP.University.Model.Subject; import ru.IP_LabWorks.IP.University.Model.Subject;
import java.util.List;
import java.util.stream.Collectors;
public class SubjectDTO { public class SubjectDTO {
private long id; private long id;
private String name; private String name;
private List<Long> groupIds;
public SubjectDTO(){ public SubjectDTO(){
} }
public SubjectDTO(Subject subject){ public SubjectDTO(Subject subject){
this.id = subject.getId(); this.id = subject.getId();
this.name = subject.getName(); this.name = subject.getName();
this.groupIds = subject.getGroupIds();
} }
public Long getId(){ public Long getId(){
@ -21,4 +25,9 @@ public class SubjectDTO {
public String getName(){ public String getName(){
return name; return name;
} }
public List<Long> getGroupIds(){
return groupIds;
}
} }

View File

@ -8,6 +8,7 @@ import ru.IP_LabWorks.IP.University.Service.GroupService;
import ru.IP_LabWorks.IP.University.Service.SubjectService; import ru.IP_LabWorks.IP.University.Service.SubjectService;
import java.util.List; import java.util.List;
import java.util.Objects;
@RestController @RestController
@RequestMapping("/subject") @RequestMapping("/subject")
@ -44,4 +45,14 @@ public class SubjectController {
public SubjectDTO deleteSubject(@PathVariable Long id){ public SubjectDTO deleteSubject(@PathVariable Long id){
return new SubjectDTO(subjectService.deleteSubject(id)); return new SubjectDTO(subjectService.deleteSubject(id));
} }
@GetMapping("/getAllSubjectGroup")
public List<Object[]> getAllSubjectGroup(){
return subjectService.getAllSubjectGroup();
}
@PostMapping("/{id}/addSubjectToGroup")
public void addSubjectToGroup(@PathVariable Long id, @RequestBody @Valid List<Long> groupsIds){
subjectService.addSubjectToGroup(id, groupsIds);
}
} }

View File

@ -85,4 +85,9 @@ public class Group {
public void setSubjects(List<Subject> subjects) { public void setSubjects(List<Subject> subjects) {
this.subjects = subjects; this.subjects = subjects;
} }
public void addSubject(Subject subject) {
subjects.add(subject);
subject.getGroups().add(this);
}
} }

View File

@ -6,6 +6,7 @@ import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction; import org.hibernate.annotations.OnDeleteAction;
import javax.swing.*; import javax.swing.*;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@ -61,4 +62,14 @@ public class Subject {
public void setGroups(List<Group> groups) { public void setGroups(List<Group> groups) {
this.groups = groups; this.groups = groups;
} }
public List<Long> getGroupIds(){
List<Long> GroupsIds = new ArrayList<>();
for(Group group : groups){
if(!GroupsIds.contains(group.getId())){
GroupsIds.add(group.getId());
}
}
return GroupsIds;
}
} }

View File

@ -1,7 +1,12 @@
package ru.IP_LabWorks.IP.University.Repository; package ru.IP_LabWorks.IP.University.Repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.IP_LabWorks.IP.University.Model.Subject; import ru.IP_LabWorks.IP.University.Model.Subject;
import java.util.List;
public interface SubjectRepository extends JpaRepository<Subject, Long> { public interface SubjectRepository extends JpaRepository<Subject, Long> {
@Query(value = "SELECT * FROM subject_group", nativeQuery = true)
List<Object[]> getAllSubjectGroup();
} }

View File

@ -1,24 +1,25 @@
package ru.IP_LabWorks.IP.University.Service; package ru.IP_LabWorks.IP.University.Service;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import ru.IP_LabWorks.IP.University.Model.Group; import ru.IP_LabWorks.IP.University.Model.Group;
import ru.IP_LabWorks.IP.University.Model.Subject; import ru.IP_LabWorks.IP.University.Model.Subject;
import ru.IP_LabWorks.IP.University.Repository.SubjectRepository; import ru.IP_LabWorks.IP.University.Repository.SubjectRepository;
import ru.IP_LabWorks.IP.University.Service.NotFoundException.GroupNotFoundException;
import ru.IP_LabWorks.IP.University.Service.NotFoundException.SubjectNotFoundException; import ru.IP_LabWorks.IP.University.Service.NotFoundException.SubjectNotFoundException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@Service @Service
public class SubjectService { public class SubjectService {
private final SubjectRepository subjectRepository; private final SubjectRepository subjectRepository;
private final GroupService groupService;
public SubjectService(SubjectRepository subjectRepository) { public SubjectService(SubjectRepository subjectRepository, GroupService groupService) {
this.subjectRepository = subjectRepository; this.subjectRepository = subjectRepository;
this.groupService = groupService;
} }
@Transactional @Transactional
@ -63,6 +64,30 @@ public class SubjectService {
subjectRepository.deleteAll(); subjectRepository.deleteAll();
} }
@Transactional
public List<Object[]> getAllSubjectGroup(){
return subjectRepository.getAllSubjectGroup();
}
@Transactional
public void addSubjectToGroup(Long subjectId, List<Long> groupIds){
final Subject currentSubject = findSubject(subjectId);
currentSubject.setGroups(new ArrayList<>());
for(Long groupId : groupIds) {
currentSubject.getGroups().add(groupService.findGroup(groupId));
}
subjectRepository.save(currentSubject);
}
// @Transactional
// public void addSubjectToGroup(List<Long> groupsId, Subject subject) {
// List<Group> groups = groupRepository.findAllById(groupsId);
// for (Group group : groups) {
// group.addSubject(subject);
// }
// groupRepository.saveAll(groups);
// }
// @Transactional // @Transactional
// public void addGroupToSubject(Long subjectId, Long groupId) { // public void addGroupToSubject(Long subjectId, Long groupId) {
// Subject subject = findSubject(subjectId); // Subject subject = findSubject(subjectId);