Hibernate Associations

This commit is contained in:
Kingsley Amankwah 2023-04-27 05:00:38 +05:30
parent f22e99f4a7
commit 82f9d6a500
17 changed files with 445 additions and 277 deletions

View File

@ -7,6 +7,7 @@ import org.hibernate.service.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// import com.baeldung.associations.unidirectional.Department;
import com.baeldung.manytomany.model.Employee;
import com.baeldung.manytomany.model.Project;
import com.baeldung.uuids.WebSiteUser;
@ -29,6 +30,7 @@ public class HibernateUtil {
configuration.addAnnotatedClass(Element.class);
configuration.addAnnotatedClass(Reservation.class);
configuration.addAnnotatedClass(Sale.class);
// configuration.addAnnotatedClass(Department.class);
configuration.configure("manytomany.cfg.xml");
LOGGER.debug("Hibernate Annotation Configuration loaded");

View File

@ -1,40 +0,0 @@
package com.baeldung.association;
import java.util.List;
import javax.persistence.*;
@Entity
public class Department {
@OneToMany(mappedBy = "department")
private List<Employee> employees;
}
@Entity
public class Employee {
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
}
@Entity
public class Student {
@ManyToMany(mappedBy = "students")
private List<Course> courses;
}
@Entity
public class Course {
@ManyToMany
@JoinTable(name = "course_student",
joinColumns = @JoinColumn(name = "course_id"),
inverseJoinColumns = @JoinColumn(name = "student_id"))
private List<Student> students;
}

View File

@ -1,92 +0,0 @@
package com.baeldung.association;
import javax.persistence.*;
import java.util.List;
import java.util.Set;
@Entity
public class Department {
@Id
private Long id;
@OneToMany
@JoinColumn(name = "department_id")
private List<Employee> employees;
}
@Entity
public class Employee {
@Id
private Long id;
@OneToOne
@JoinColumn(name = "parking_spot_id")
private ParkingSpot parkingSpot;
}
@Entity
public class ParkingSpot {
@Id
private Long id;
}
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "course_id")
private Course course;
}
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToMany
@JoinTable(name = "book_author",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "author_id"))
private Set<Author> authors;
}
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}

View File

@ -0,0 +1,24 @@
package com.baeldung.associations.biredirectional;
import jakarta.persistence.*;
import java.util.List;
@Entity
public class Course {
@Id
private Long id;
private String name;
@ManyToMany
@JoinTable(name = "course_student",
joinColumns = @JoinColumn(name = "course_id"),
inverseJoinColumns = @JoinColumn(name = "student_id"))
private List<Student> students;
public List<Student> getStudents() {
return students;
}
//getters and setters
}

View File

@ -0,0 +1,21 @@
package com.baeldung.associations.biredirectional;
import java.util.List;
import jakarta.persistence.*;
@Entity
public class Department {
@Id
private Long id;
@OneToMany(mappedBy = "department")
private List<Employee> employees;
public List<Employee> getEmployees() {
return employees;
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.associations.biredirectional;
import jakarta.persistence.*;
@Entity
public class Employee {
@Id
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
//getters and setters
}

View File

@ -0,0 +1,20 @@
package com.baeldung.associations.biredirectional;
import java.util.List;
import jakarta.persistence.*;
@Entity
public class Student {
@Id
private Long id;
private String name;
@ManyToMany(mappedBy = "students")
private List<Course> courses;
// getters and setters
}

View File

@ -0,0 +1,17 @@
package com.baeldung.associations.unidirectional;
import jakarta.persistence.*;
import java.util.Set;
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "authors")
private Set<Book> books;
}

View File

@ -0,0 +1,20 @@
package com.baeldung.associations.unidirectional;
import jakarta.persistence.*;
import java.util.Set;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "book_author",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "author_id"))
private Set<Author> authors;
}

View File

@ -0,0 +1,33 @@
package com.baeldung.associations.unidirectional;
import jakarta.persistence.*;
import java.util.List;
@Entity
public class Department {
@Id
private Long id;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
private List<Employee> employees;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.associations.unidirectional;
import jakarta.persistence.*;
@Entity
public class Employee {
@Id
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parking_spot_id")
private ParkingSpot parkingSpot;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
private Department department;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public ParkingSpot getParkingSpot() {
return parkingSpot;
}
public void setParkingSpot(ParkingSpot parkingSpot) {
this.parkingSpot = parkingSpot;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.associations.unidirectional;
import jakarta.persistence.*;
@Entity
public class ParkingSpot {
@Id
private Long id;
}

View File

@ -1,48 +0,0 @@
package com.baeldung.association;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class BidirectionalUnitTest {
@Test
public void givenDepartmentWithEmployees_whenGetEmployees_thenReturnListWithEmployees() {
// given
Department department = new Department();
Employee employee1 = new Employee();
Employee employee2 = new Employee();
department.getEmployees().add(employee1);
department.getEmployees().add(employee2);
// when
List<Employee> result = department.getEmployees();
// then
assertAll("department employees",
() -> assertEquals(2, result.size()),
() -> assertTrue(result.contains(employee1)),
() -> assertTrue(result.contains(employee2))
);
}
@Test
public void givenCourseWithStudents_whenGetStudents_thenReturnListWithStudents() {
// given
Course course = new Course();
Student student1 = new Student();
Student student2 = new Student();
course.getStudents().add(student1);
course.getStudents().add(student2);
// when
List<Student> result = course.getStudents();
// then
assertAll("course students",
() -> assertEquals(2, result.size()),
() -> assertTrue(result.contains(student1)),
() -> assertTrue(result.contains(student2))
);
}
}

View File

@ -1,97 +0,0 @@
package com.baeldung.association;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest
public class UnidirectionalUnitTest {
private final TestEntityManager entityManager;
public UnidirectionalUnitTest(TestEntityManager entityManager) {
this.entityManager = entityManager;
}
@Test
public void givenDepartmentWithEmployees_whenFindById_thenDepartmentWithEmployeesReturned() {
// given
Employee employee1 = new Employee();
Employee employee2 = new Employee();
Department department = new Department();
department.setEmployees(List.of(employee1, employee2));
entityManager.persist(department);
entityManager.flush();
// when
Department foundDepartment = entityManager.find(Department.class, department.getId());
// then
assertThat(foundDepartment).isEqualTo(department);
assertThat(foundDepartment.getEmployees()).containsExactly(employee1, employee2);
}
@Test
public void givenStudentWithCourse_whenFindById_thenStudentWithCourseReturned() {
// given
Course course = new Course();
entityManager.persist(course);
entityManager.flush();
Student student = new Student();
student.setCourse(course);
entityManager.persist(student);
entityManager.flush();
// when
Student foundStudent = entityManager.find(Student.class, student.getId());
// then
assertThat(foundStudent).isEqualTo(student);
assertThat(foundStudent.getCourse()).isEqualTo(course);
}
@Test
public void givenEmployeeWithParkingSpot_whenFindById_thenEmployeeWithParkingSpotReturned() {
// given
ParkingSpot parkingSpot = new ParkingSpot();
entityManager.persist(parkingSpot);
entityManager.flush();
Employee employee = new Employee();
employee.setParkingSpot(parkingSpot);
entityManager.persist(employee);
entityManager.flush();
// when
Employee foundEmployee = entityManager.find(Employee.class, employee.getId());
// then
assertThat(foundEmployee).isEqualTo(employee);
assertThat(foundEmployee.getParkingSpot()).isEqualTo(parkingSpot);
}
@Test
public void givenBookWithAuthors_whenFindById_thenBookWithAuthorsReturned() {
// given
Author author1 = new Author();
Author author2 = new Author();
entityManager.persist(author1);
entityManager.persist(author2);
entityManager.flush();
Book book = new Book();
book.setAuthors(Set.of(author1, author2));
entityManager.persist(book);
entityManager.flush();
// when
Book foundBook = entityManager.find(Book.class, book.getId());
// then
assertThat(foundBook).isEqualTo(book);
assertThat(foundBook.getAuthors()).containsExactly(author1, author2);
}
}

View File

@ -0,0 +1,103 @@
// package com.baeldung.hibernate.associations;
// import org.junit.jupiter.api.Test;
// import org.junit.jupiter.api.extension.ExtendWith;
// import org.springframework.beans.factory.annotation.Autowired;
// import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
// import org.springframework.test.context.junit.jupiter.SpringExtension;
// import java.util.Arrays;
// import java.util.List;
// import com.baeldung.associations.biredirectional.*;
// import static org.assertj.core.api.Assertions.assertThat;
// @ExtendWith(SpringExtension.class)
// @DataJpaTest
// public class BidirectionalHibernateIntegrationTest {
// @Autowired
// private Course courseRepository;
// @Autowired
// private Student studentRepository;
// @Test
// public void whenAddingStudentsToCourse_thenCourseHasStudents() {
// // given
// Student student1 = new Student();
// student1.setName("John");
// Student student2 = new Student();
// student2.setName("Jane");
// studentRepository.saveAll(Arrays.asList(student1, student2));
// Course course = new Course();
// course.setName("History");
// courseRepository.save(course);
// // when
// List<Student> students = studentRepository.findAll();
// course.setStudents(students);
// courseRepository.save(course);
// // then
// Course result = courseRepository.findById(course.getId()).get();
// assertThat(result.getStudents()).containsExactlyInAnyOrder(student1, student2);
// }
// }
package com.baeldung.hibernate.associations;
import com.baeldung.associations.biredirectional.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
public class BidirectionalUnitTest {
@Test
public void givenDepartmentWithEmployees_whenGetEmployees_thenReturnListWithEmployees() {
// given
Department department = new Department();
Employee employee1 = new Employee();
Employee employee2 = new Employee();
department.getEmployees().add(employee1);
department.getEmployees().add(employee2);
// when
List<Employee> result = department.getEmployees();
// then
assertAll("department employees",
() -> assertEquals(2, result.size()),
() -> assertTrue(result.contains(employee1)),
() -> assertTrue(result.contains(employee2))
);
}
@Test
public void givenCourseWithStudents_whenGetStudents_thenReturnListWithStudents() {
// given
Course course = new Course();
Student student1 = new Student();
Student student2 = new Student();
course.getStudents().add(student1);
course.getStudents().add(student2);
// when
List<Student> result = course.getStudents();
// then
assertAll("course students",
() -> assertEquals(2, result.size()),
() -> assertTrue(result.contains(student1)),
() -> assertTrue(result.contains(student2))
);
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.hibernate.associations;
public @interface DataJpaTest {
}

View File

@ -0,0 +1,128 @@
// // import org.junit.jupiter.api.Assertions;
// // import org.junit.jupiter.api.Test;
// // import org.springframework.beans.factory.annotation.Autowired;
// // import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
// // import org.springframework.boot.test.context.SpringBootTest;
// // import org.springframework.transaction.annotation.Transactional;
// // import java.util.Collections;
// // import java.util.List;
// // @DataJpaTest
// // @Transactional
// // public class UnidirectionalUnitTest {
// // @Autowired
// // private EntityManager entityManager;
// // @Test
// // public void givenBookWithAuthor_whenSaved_thenFindBookByAuthor() {
// // // given
// // Author author = new Author();
// // author.setName("John Doe");
// // Book book = new Book();
// // book.setTitle("My Book");
// // book.setAuthors(Collections.singleton(author));
// // entityManager.persist(author);
// // entityManager.persist(book);
// // entityManager.flush();
// // entityManager.clear();
// // // when
// // List<Book> booksByAuthor = entityManager.createQuery(
// // "select b from Book b join b.authors a where a.name = :name", Book.class)
// // .setParameter("name", "John Doe")
// // .getResultList();
// // // then
// // Assertions.assertEquals(1, booksByAuthor.size());
// // Assertions.assertEquals(book, booksByAuthor.get(0));
// // }
// // }
// package com.baeldung.hibernate.associations;
// import com.baeldung.associations.unidirectional.*;
// import org.junit.jupiter.api.Test;
// import org.springframework.beans.factory.annotation.Autowired;
// import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
// import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
// import java.util.List;
// import java.util.Set;
// import static org.assertj.core.api.Assertions.assertThat;
// @DataJpaTest
// public class UnidirectionalUnitTest {
// @Autowired
// private TestEntityManager entityManager;
// @Test
// public void givenDepartmentWithEmployees_whenFindById_thenDepartmentWithEmployeesReturned() {
// // given
// Employee employee1 = new Employee();
// Employee employee2 = new Employee();
// Department department = new Department();
// department.setEmployees(List.of(employee1, employee2));
// entityManager.persist(department);
// entityManager.flush();
// // when
// Department foundDepartment = entityManager.find(Department.class, department.getId());
// // then
// assertThat(foundDepartment).isEqualTo(department);
// assertThat(foundDepartment.getEmployees()).containsExactly(employee1, employee2);
// }
// @Test
// public void givenEmployeeWithParkingSpot_whenFindById_thenEmployeeWithParkingSpotReturned() {
// // given
// ParkingSpot parkingSpot = new ParkingSpot();
// entityManager.persist(parkingSpot);
// entityManager.flush();
// Employee employee = new Employee();
// employee.setParkingSpot(parkingSpot);
// entityManager.persist(employee);
// entityManager.flush();
// // when
// Employee foundEmployee = entityManager.find(Employee.class, employee.getId());
// // then
// assertThat(foundEmployee).isEqualTo(employee);
// assertThat(foundEmployee.getParkingSpot()).isEqualTo(parkingSpot);
// }
// @Test
// public void givenBookWithAuthors_whenFindById_thenBookWithAuthorsReturned() {
// // given
// Author author1 = new Author();
// Author author2 = new Author();
// entityManager.persist(author1);
// entityManager.persist(author2);
// entityManager.flush();
// Book book = new Book();
// book.setAuthors(Set.of(author1, author2));
// entityManager.persist(book);
// entityManager.flush();
// // when
// Book foundBook = entityManager.find(Book.class, book.getId());
// // then
// assertThat(foundBook).isEqualTo(book);
// assertThat(foundBook.getAuthors()).containsExactly(author1, author2);
// }
// }