I have a Hibernate entity that has recursive relationship to itself (parent-children). And I use DbUnit XML file to insert some data in my tests, including a relationship.
However, on my service under test that queries for the list of parent=null (roots) I also get the child specified in the XML as a root too (also having parent = null).
Why is this happening?
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames={"parent", "name"}))
public class Entity {
@Id
@Column(name = "id", unique = true)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name", nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "parent")
private Entity parent;
@OneToMany(mappedBy = "parent")
private List<Entity> children;
}
And the XML dataset file:
<dataset>
<entity id="1" name="root1" />
<entity id="2" name="root2" />
<entity id="3" name="child" parent="2"/>
</dataset>
When listing the roots I also get the 'child' entity with parent property null.
If I create the relationship using entity instances and persist them, it works.
Also I have yet another entity with many-to-one relationship to different entity (no recursion) and this works as expected using DbUnit dataset XML. It seems that it has some problem with recursive entites.
The problem is that, DbUnit considers only the column names from the first occurence of the table tag in the Flat XML dataset. So the 'parent' column in the following tags was ignored.
However, as I need to insert the root folder first, I need the 'parent' column to be null. But in Flat XML dataset, null values are handled by ommiting the column, which goes against the previous statement.
Solution is not to use Flat XML dataset, but normal and more verbose Xml DataSet which provides tag that can be used for null value columns.