You are given a simple class diagram of a 1-to-many relationship between Department and Employee, such that each Employee belongs to only one Department. Each Department can have many Employees.
What are the key annotations?
@Entity – marks class as a JPA entity (database table)@Id – designates primary key@GeneratedValue(strategy = GenerationType.AUTO) – database chooses PK generation strategy@Column(nullable = false) – name fields cannot be empty@ManyToOne – many employees belong to one department@OneToMany(mappedBy = "department") – one department has many employees; mappedBy indicates Employee owns the relationship@JoinColumn – specifies the foreign key columnWhat is the code for the Department Entity
@Entity
public class Department{
@Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(nullable=false) private String name; @OneToMany(mappedBy = "department") private List<Employee> employees; // getters and setters
}
What is the code for the Employee Entity
@Entity
public class Employee{
@Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(nullable=false) private String firstName; @Column(nullable=false) private String lastName; private LocalDate birthdate; private String phone; private String email; @ManyToOne @JoinColumn(name = "department_id") private Department department; //getters and setters }
Write the CRUD Repository class for Employee, and include methods to implement the following
queries:
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
List<Employee> findByFirstNameContaining(String substring); List<Employee> findByBirthdateBetween(LocalDate startDate, LocalDate endDate); List<Employee> findBySurname(String surname); List<Employee> findByFirstName(String firstName); List<Employee> findByFirstAndLastName(String firstName, String surname);
@Query(“SELECT e FROM Employee e WHERE e.department.name = :deptName”);
List<Employee> findByDepartmentName(@Param("deptName") String departmentName);</Employee>