Given the following Spring Boot entities, what will be printed when fetching a User and printing its Address street?
public class User { @Id private Long id; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "address_id") private Address address; public Address getAddress() { return address; } } public class Address { @Id private Long id; private String street; public String getStreet() { return street; } } // Assume userRepository.findById(1L) returns a User with Address street = "Main St"
Consider the default fetch type of @OneToOne and if the session is open when accessing the address.
By default, @OneToOne uses EAGER fetching, so the Address is loaded with the User. Therefore, printing the street outputs "Main St".
Choose the correct code snippet that sets up a bidirectional @OneToOne relationship between User and Profile entities.
Remember the owning side has the @JoinColumn annotation and the inverse side uses mappedBy.
The owning side is Profile with @JoinColumn. User uses mappedBy to point to Profile's user field. This setup creates a bidirectional @OneToOne.
Consider this code snippet:
public class Employee {
@OneToOne
private ParkingSpot spot;
}
public class ParkingSpot {
@OneToOne
private Employee employee;
}When saving an Employee, a runtime exception occurs. What is the cause?
Check which side owns the relationship and if the foreign key column is defined.
Without @JoinColumn on one side, Hibernate cannot know which table owns the foreign key, causing a runtime error.
Given these entities:
public class User {
@Id
private Long id;
@OneToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "address_id")
private Address address;
}
public class Address {
@Id
private Long id;
private String city;
}If you create a User and set a new Address (without saving Address separately) and then save User, what happens in the database?
Think about what CascadeType.PERSIST does when saving related entities.
CascadeType.PERSIST causes the Address to be saved automatically when saving User, so both are persisted and linked.
Consider the default fetch types in JPA for @OneToOne and @ManyToOne. Which statement is correct?
Recall the JPA specification defaults for fetch types on these annotations.
@OneToOne defaults to EAGER fetch, meaning related entities load immediately, which can impact performance if not handled carefully.