在hibernate和spring中加入交叉引用表

时间:2014-06-30 10:33:57

标签: java sql spring hibernate

我使用hibernate和spring-data。有两个表具有多对多关系。

@Entity
@Table(name = "FirstEntity")
public class FirstEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "first_entity_id")
    private Long id;

    @Column(name = "first_entiry_name")
    private String name;

    /* getters and setters are below*/
}

@Entity
@Table(name = "SecondEntity")
public class SecondEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "second_entity_id")
    private Long id;

    @Column(name = "second_entiry_name")
    private String name;

    @Column(name = "second_entiry_desc")
    private String description;

    /* getters and setters are below*/
}

交叉引用表的实体。

@Entity
@Table(name = "FirstSecondEntity")
public class FirstSecondEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "first_second_entity_id")
    private Long id;

    @Column(name = "first_entity_id")
    private Long firstEntityId;

    @Column(name = "second_entity_id")
    private Long secondEntityId;

    /* getters and setters are below*/
}

我需要像这样选择

SELECT FirstEntity.name, SecondEntity.name, SecondEntity.description FROM SecondEntity INNER JOIN FirstSecondEntity ON SecondEntity.id = FirstSecondEntity.secondEntityId INNER JOIN User ON FirstEntity.id = FirstSecondEntity.firstEntityId

即。我需要来自交叉引用表的所有记录,而不是id,而是来自实体的实际信息。 由于

,在CrudRepository扩展类中将此查询插入@Query注释不起作用
ERROR [main][org.hibernate.hql.internal.ast.ErrorCounter]  Path expected for join!

所以我需要你的帮助。

1 个答案:

答案 0 :(得分:0)

您的联接表已全部搞砸了。在这种情况下,您实际上甚至不需要将连接表作为hibernate映射:

在Second Entity中添加以下列表:

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "FirstSecondEntity",
        joinColumns = {
                @JoinColumn(name = "first_entity_id",
                        nullable = false,
                        updatable = false) },
        inverseJoinColumns = {
                @JoinColumn(name = "second_entity_id",
                        nullable = false,
                        updatable = false) },
        )
private List<FirstEntity> firstEntities;

在FirstEntity中添加以下列表:

@ManyToMany(fetch = FetchType.LAZY,
        mappedBy = "firstEntities")
private List<SecondEntity> secondEntities;