I want to implement Null Object pattern for Hibernate Entity.
Let's assume we have Person
entity with Address
field. In one case Address of Person must be defined in other may not be defined.
@Entity
class Person {
String name;
@ManyToOne(targetEntity = Address.class)
IAddress address;
public Person(String name, IAddress address) {
this.name = name;
this.address = address;
}
}
interface IAddress {
String getCity();
String getStreet();
}
@Entity
class Address implements IAddress {
@Id
private Integer id;
private String city;
private String street;
public Address(String city, String street) {
this.city = city;
this.street = street;
}
@Override
public String getCity() {
return city;
}
@Override
public String getStreet() {
return street;
}
}
class NullObjectAddress implements IAddress {
@Override
public String getCity() {
return "London";
}
@Override
public String getStreet() {
return "Baker street";
}
}
I try to save Person
Person per1 = new Person("Jhon Doe", new Address("Huge village", "main street"));
personRepository.save(per1); //that`s ok
Person per2 = new Person("Jhon Doe", new NullObjectAddress());
personRepository.save(per2); //throws exception
Exception is:
org.springframework.orm.jpa.JpaSystemException: Error accessing field [private Address.id] by reflection for persistent property [Person#id] : NullObjectAddress@3638120f; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Int Person.id] by reflection for persistent property [Person#id] : NullObjectAddress@3638120f
address
field to null ... like you would in normal Java. Can't your JPA provider cope with that? Seems that it insists it has to be of the "targetEntity" type, no? – Neil Stockton Apr 4 '17 at 13:06