Spring Boot Data Persistence with JPA 2 — Questions and Answers
Question 1: Which annotation marks a field as the primary key in a JPA entity?
- @PrimaryKey
- @Id (Correct answer)
- @Key
- @GeneratedId
Correct answer: @Id
@Id designates the field as the entity's primary key in JPA.
Question 2: What does the `cascade = CascadeType.ALL` attribute do in a JPA relationship?
- Deletes all orphaned records only
- Propagates all persistence operations from parent to child (Correct answer)
- Merges duplicate entities
- Enables lazy loading on the association
Correct answer: Propagates all persistence operations from parent to child
CascadeType.ALL propagates persist, merge, remove, refresh, and detach operations from the owning entity to related entities.
Question 3: Which Spring Data JPA method naming convention generates a query that finds entities by two fields using AND logic?
- findByFieldOneOrFieldTwo
- findByFieldOneAndFieldTwo (Correct answer)
- findAllByFieldOneWithFieldTwo
- queryByFieldOnePlusFieldTwo
Correct answer: findByFieldOneAndFieldTwo
Spring Data JPA parses method names using keywords like 'And' to combine conditions in the generated query.
Question 4: What is the purpose of `@Column(nullable = false)` in a JPA entity?
- Sets a default value for the column
- Marks the column as the primary key
- Adds a NOT NULL constraint to the database column (Correct answer)
- Enables unique constraint on that column
Correct answer: Adds a NOT NULL constraint to the database column
`nullable = false` instructs the schema generation tool to add a NOT NULL constraint to the mapped column.
Question 5: Which `FetchType` loads a collection only when it is accessed for the first time?
- FetchType.EAGER
- FetchType.IMMEDIATE
- FetchType.LAZY (Correct answer)
- FetchType.DEFERRED
Correct answer: FetchType.LAZY
FetchType.LAZY defers loading of a related collection until the application explicitly accesses it.
Question 6: What does `@GeneratedValue(strategy = GenerationType.IDENTITY)` tell JPA?
- The application must assign the ID before saving
- The database auto-increments the primary key column (Correct answer)
- A sequence object generates the key
- A UUID is used as the key
Correct answer: The database auto-increments the primary key column
GenerationType.IDENTITY relies on the database's auto-increment capability to generate primary key values.
Question 7: Which annotation defines a bi-directional one-to-many relationship's inverse (non-owning) side?
- @JoinColumn
- @MappedBy on @OneToMany (Correct answer)
- @PrimaryJoinColumn
- @InverseJoinColumn
Correct answer: @MappedBy on @OneToMany
The `mappedBy` attribute on @OneToMany points to the field on the owning side, marking this side as the inverse.
Which annotation marks a field as the primary key in a JPA entity?