JPA Flashcards

(4 cards)

1
Q

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?

A
  • @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 column
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the code for the Department Entity

A

@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

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the code for the Employee Entity

A

@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 }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Write the CRUD Repository class for Employee, and include methods to implement the following

queries:

  • Find Employees whose first name contains a specific substring
  • Find Employees whose date of birth is between specific dates
  • Find Employees by surname and first name.
  • Any custom query defined using the @Query annotation
A

@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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly