This commit is contained in:
ArtemEmelyanov 2023-04-14 22:00:27 +04:00
parent 4f9bba63ee
commit 8595331a1d
3 changed files with 65 additions and 0 deletions

Binary file not shown.

View File

@ -0,0 +1,4 @@
package ru.IP_LabWorks.IP.University.Service;
public class GroupService {
}

View File

@ -1,4 +1,65 @@
package ru.IP_LabWorks.IP.University.Service; package ru.IP_LabWorks.IP.University.Service;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import ru.IP_LabWorks.IP.University.Model.Student;
import java.util.List;
@Service
public class StudentService { public class StudentService {
@PersistenceContext
private EntityManager em;
@Transactional
public Student addStudent(String name, Integer age){
if (!StringUtils.hasText(name) || !StringUtils.hasText(String.valueOf(age))) {
throw new IllegalArgumentException("Student name or age is null or empty");
}
final Student student = new Student(name, age);
em.persist(student);
return student;
}
@Transactional(readOnly = true)
public Student findStudent(Long id) {
final Student student = em.find(Student.class, id);
if (student == null) {
throw new EntityNotFoundException(String.format("Student with id [%s] is not found", id));
}
return student;
}
@Transactional(readOnly = true)
public List<Student> findAllStudents() {
return em.createQuery("select s from Student s", Student.class).getResultList();
}
@Transactional
public Student updateStudent(Long id, String name, Integer age) {
if (!StringUtils.hasText(name) || !StringUtils.hasText(String.valueOf(age))) {
throw new IllegalArgumentException("Student name or age is null or empty");
}
final Student currentStudent = findStudent(id);
currentStudent.setName(name);
currentStudent.setAge(age);
return em.merge(currentStudent);
}
@Transactional
public Student deleteStudent(Long id) {
final Student currentStudent = findStudent(id);
em.remove(currentStudent);
return currentStudent;
}
@Transactional
public void deleteAllStudent() {
em.createQuery("delete from Student").executeUpdate();
}
} }