在递归 table 上找不到 Hibernate 根项目

Hibernate root item not found on recursive table

当我尝试获取递归的根节点时 table hibernate 找不到它。

Table 架构:

+----------+------------------+------+-----+---------+----------------+
| Field    | Type             | Null | Key | Default | Extra          |
+----------+------------------+------+-----+---------+----------------+
| id       | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| idbox    | int(10) unsigned | NO   | MUL | NULL    |                |
| idparent | int(10) unsigned | YES  | MUL | NULL    |                |
| nom      | text             | NO   |     | NULL    |                |
+----------+------------------+------+-----+---------+----------------+

数据的selecttable:

+----+-------+----------+----------------+
| id | idbox | idparent | nom            |
+----+-------+----------+----------------+
|  1 |     1 |       16 | RDC            |
|  2 |     1 |        1 | salon          |
|  3 |     1 |        1 | cuisine        |
|  4 |     1 |        1 | room invite    |
|  5 |     1 |       16 | etage 1        |
|  6 |     1 |        5 | room parent    |
|  7 |     1 |        5 | room david     |
|  8 |     1 |        5 | room sarah     |
|  9 |     1 |        5 | room rachel    |
| 10 |     1 |        5 | room leon      |
| 11 |     1 |       16 | etage 2        |
| 12 |     1 |       11 | grenier        |
| 13 |     1 |        5 | WC             |
| 14 |     1 |        5 | SDB            |
| 15 |     1 |        6 | SDB-Parent     |
| 16 |     1 |     NULL | root           |
+----+-------+----------+----------------+

class 位置:

public class Position implements Serializable, Comparable<Position>
{
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(unique=true, nullable=false)
    private int id;

    @Lob
    @Column(nullable=false)
    private String nom;

    //bi-directional many-to-one association to Dispositif
    @OneToMany(mappedBy="position")
    private Set<Dispositif> dispositifs;

    //bi-directional many-to-one association to Box
    @ManyToOne
    @JoinColumn(name="idbox", nullable=false)
    private Box box;

    //bi-directional many-to-one association to Position
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="idparent", nullable=false)
    private Position parent;

    //bi-directional many-to-one association to Position
    @OneToMany(mappedBy="parent",  orphanRemoval=true, cascade = CascadeType.ALL )
    private Set<Position> positions = new HashSet<Position>();
    ...
}

所以当我在我的休眠查询中添加一个条件时(我通过 idbox=1 和 name='root' 搜索)结果是空的

仅当idparent设置为NULL时出现问题

2) 我需要自己引用根吗?

知道为什么吗? 谢谢

问题的原因是您已将 idparent 连接列定义为不可空,即使您的数据库明确允许此列的 NULL 值。

基于此Hibernate会认为父ID不能包含空值,这会影响它生成的SQL代码。在您的情况下,它导致使用您在评论中提到的 INNER JOIN

要修复它,请像这样使连接列可为空:@JoinColumn(name="idparent")(如果您查看其来源,默认情况下它是可为空的,因此无需明确指定)。