I am using an Interceptor to set the Id for certain classes which are instances of LocallyGeneratedIdObject. However, my implementation of the Interceptor is never called as it is failing before it can be executed. I could determine that Hibernate is using both an PojoEntityTuplizer instance and an Assigned instance, it fails when it reads the getId() method of my class as it returns null.
My class is very simple
Code:
@Entity
@Table(name="AttributeValue")
@Immutable
public class AttributeValue implements Serializable, LocallyGeneratedIdObject{
private String value;
private Long id;
public AttributeValue(){}
public AttributeValue(String value) {
super();
this.value = value;
}
@Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="value", length=50)
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append(this.value);
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (getClass() != obj.getClass())
return false;
AttributeValue other = (AttributeValue) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
@Override
public void setGeneratedId(Long id) {
this.id = id;
}
}
This is my interceptor's code that generates the Id
Code:
public class BaseEntityInterceptor extends EmptyInterceptor{
private LocalIdGenerator localIdGenerator;
@Override
public boolean onSave(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
if (entity instanceof LocallyGeneratedIdObject){
((LocallyGeneratedIdObject) entity).setGeneratedId(localIdGenerator.getNextId());
return true;
}
return super.onSave(entity, id, state, propertyNames, types);
}
@Override
public String onPrepareStatement(String sql) {
return super.onPrepareStatement(sql);
}
public LocalIdGenerator getLocalIdGenerator() {
return localIdGenerator;
}
public void setLocalIdGenerator(LocalIdGenerator localIdGenerator) {
this.localIdGenerator = localIdGenerator;
}
}
Any ideas on how to use my interceptor without getting this exception?
Thanks,
Juan