This can be easily reproduced with classes described below. If the city field and all the other possible fields of an Address object are null, Hibernate will store the Address to the database as one would expect. When getting the User back from the database the address will not be included in the addresses list. The addresses list does not obviously represent the state of the database. If Hibernate treats object with all null fields as non-existent then it does not make sense to store them the database in the first place.
A much bigger problem than the previously described one is caused when someone wants to delete the user from the database and the tables have been generated by Hibernate. Hibernate sets "ON UPDATE NO ACTION ON DELETE NO ACTION" foreign key constraint from the address table to the user table. Hibernate apparently uses the previously described logic when deleting the rows from address table that are referencing the user to be deleted. If all the addresses have only null values in their fields then Hibernate thinks that there are no addresses referencing the user table and does not execute "DELETE FROM user WHERE user_id = ?" query. This results in foreign key constraint violation.
@Entity
public class User {
@ElementCollection
public List<Address> addresses...
}
@Embeddable
public class Address {
private String city...
}
|