I am experimenting with jpa and hibernate relations. I'm using a table named users and a table named emails. A user can have many emails.
When I run my Spring boot application along with the following code I get one email record in my h2 database. The email_address of this record is testAddress and the user_username column of this record is null. The user_username column is listed as a foreign key on the emails table. My question is, why is emailRepository.save(email1) successful when there is no corresponding user in the database?
@Entity
@Table(name = "emails")
public class Email {
@Id
private String emailAddress;
@ManyToOne
private User user;
...
}
@Entity
@Table(name = "users")
public class User {
@Id
private String username;
@OneToMany(mappedBy="user", cascade=CascadeType.ALL, orphanRemoval=true)
private Set<Email> emails;
...
}
public interface UserRepository extends JpaRepository<User, String> {
}
public interface EmailRepository extends JpaRepository<Email, String> {
}
@Component
public class UserRepositoryCommandLineRunner implements CommandLineRunner {
@Autowired
private EmailRepository emailRepository;
public void run(String... args) throws Exception {
Email email1 = new Email();
email1.setEmailAddress("testAddress");
emailRepository.save(email1);
}
}