Last active
October 12, 2024 12:20
-
-
Save sunmeat/456994ef3dcf484226f989e6adffa772 to your computer and use it in GitHub Desktop.
HQL mapping example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Course.java: | |
... | |
@Entity | |
@Table(name = "courses") | |
public class Course { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Long id; | |
private String title; | |
@ManyToMany(mappedBy = "courses") // связь с Student через маппинг | |
private List<Student> students; | |
... | |
} | |
===================================================================================== | |
Student.java: | |
... | |
@Entity | |
@Table(name = "students") | |
public class Student { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Long id; | |
private String name; | |
private String email; | |
@ManyToMany // связь с Course через маппинг | |
@JoinTable( | |
name = "student_courses", | |
joinColumns = @JoinColumn(name = "student_id"), | |
inverseJoinColumns = @JoinColumn(name = "course_id") | |
) | |
private List<Course> courses; | |
... | |
} | |
===================================================================================== | |
StudentService.java: | |
... | |
@Service | |
public class StudentService { | |
@Autowired | |
private StudentRepo studentRepository; | |
@PersistenceContext | |
private EntityManager entityManager; | |
// HQL-запрос: получение всех курсов для студента по ID | |
@Transactional(readOnly = true) | |
public List<Course> findCoursesByStudentId(Long studentId) { | |
String hql = "SELECT s.courses FROM Student s WHERE s.id = :studentId"; // использование маппинга | |
return entityManager.createQuery(hql, Course.class) | |
.setParameter("studentId", studentId) | |
.getResultList(); | |
} | |
// HQL-запрос: получение всех студентов, записанных на курс | |
@Transactional(readOnly = true) | |
public List<Student> findStudentsByCourseTitle(String courseTitle) { | |
String hql = "SELECT s FROM Student s JOIN s.courses c WHERE c.title = :courseTitle"; // использование маппинга | |
return entityManager.createQuery(hql, Student.class) | |
.setParameter("courseTitle", courseTitle) | |
.getResultList(); | |
} | |
// HQL-запрос: добавление курса для студента | |
@Transactional | |
public void addCourseToStudent(Long studentId, Long courseId) { | |
Student student = studentRepository.findById(studentId) | |
.orElseThrow(() -> new EntityNotFoundException("Студент с ID " + studentId + " не найден")); | |
Course course = entityManager.find(Course.class, courseId); | |
if (course == null) { | |
throw new EntityNotFoundException("Курс с ID " + courseId + " не найден"); | |
} | |
student.getCourses().add(course); // использование маппинга для добавления курса | |
studentRepository.save(student); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment