self referencing entiy [message #382528] |
Thu, 16 October 2008 00:11  |
Eclipse User |
|
|
|
I have the following
@Entity
public class User {
@Id
@GeneratedValue(strategy = SEQUENCE)
@Column(name = "id", nullable = false, updatable = false)
private Long id = null;
@OneToOne
@JoinColumn(name = "created_by", updatable = false, nullable = false)
private User createdBy;
...
}
Then I persist it
User u = new User();
u.setCreatedBy(u);
em.persist(u);
As you see the user creator is himself.
I get the error of:
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column
"created_by" violates not-null constraint
I understand why this may happen. That at insert time the createdBy user
does not have an id yet. But since eclipselink already has it by getting
the next sequence value, I would hope it would assign it before trying to
do the insert.
Eclipselink should be able to handle this situation without me having to
take away my not null constraint so another update can make the user's
creator himself.
Am I correct in saying that this is not supported or am I doing something
wrong?
What is the process for eclipselink to get and assign the sequence value
to the object? Does it get the next sequence value, then insert, then
update the entity? Would it make sence to have eclipselink get then next
sequence value, update the enity then do the insert so the sequnce value
can be used in other columns?
I hope I explained myself clearly enough.
|
|
|
|
|
Re: self referencing entiy [message #382533 is a reply to message #382528] |
Thu, 16 October 2008 13:07  |
Eclipse User |
|
|
|
I was able to get this to work by creating an DescriptorEventAdapter.
This is a hack and hopefully eclipselink will fix the bug.
public class AuditHandler extends DescriptorEventAdapter implements
DescriptorCustomizer {
public void customize(ClassDescriptor classDescriptor) throws Exception {
classDescriptor.getDescriptorEventManager().addListener(this );
}
@Override
public void aboutToInsert(DescriptorEvent event) {
AuditableModelBase source = (AuditableModelBase) event.getSource();
event.updateAttributeWithObject("createdBy", source.getCreatedBy());
}
|
|
|
Powered by
FUDForum. Page generated in 0.07073 seconds