I’ve got a web application accessing a database with a table named “parent”. This parent has children which can also be parent of more children:
public class Thing extends Entity{
@OneToMany(cascade = {CascadeType.ALL})
@JoinColumn(name = "parent_id")
private List<Thing> children = new ArrayList<Thing>();
@Column
private String property;
public String getProperty() { return property; }
public void setProperty(String property) { this.property = property; }
Entity has got the PK property:
@Id
@Column(nullable = false)
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
Now, I want to access from an HQL query to the parent_id property of a Thing. If I just do:
[Another class]
Query queryParents = getEntityManager().createQuery("from Thing t where t.parent_id is null");
I get an error saying the property does not exist. Well, I add the following to the Thing class:
@Column
private Long parent_id;
public Long getParent_id() { return parent_id; }
public void setParent_id(Long parent_id) { this.parent_id = parent_id; }
And that seems to work, but I think that is not correct because they do not reference to the same entity… in fact, trying to update a Thing object, will end up in a “org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): …”.
So, what is the correct way to return the parent_id property of an Entity “Thing” [database has a column ‘parent_id’ for the object Thing], if the class Thing itself hasn’t got the property? I’m a newby with all these stuff…
The database has a parent_id field for every Thing, which is null for root parents, and contains the parent id for everything else.
Thanks in advance.
Make your association bidirectional:
And the query will simply be
Returning the parent ID will be:
Read more about bidirectional associations in the Hibernate documentation.