HQL多对多加入额外列

时间:2017-09-11 14:51:35

标签: mysql sql hibernate many-to-many hql

我在Hibernate中有多对多的关系额外的colums 所以我有一个额外的java类用于模型和另一个带有主键的类...现在在HQL中我需要一个查询检索这些数据,但我遇到加入条件的问题。

这是我的第一堂课:

@Entity
@Table(name = "Firsts")
public class First {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @OneToMany(mappedBy = "primaryKey.second")
    private List<FirstsSeconds> seconds = new LinkedList<>();
    @Column(name="description")
    private String description;
    ...
}

第二课:

@Entity
@Table(name="Seconds")
public class Second {
    @Id
    private String code;

    @OneToMany(mappedBy = "primaryKey.first")
    private List<FirtsSeconds> firsts = new LinkedList<>();

    ...
}

表manyToMany还有其他列:

@Entity
@Table(name = "firsts_seconds")
@AssociationOverrides({ @AssociationOverride(name = "primaryKey.first", joinColumns = @JoinColumn(name = "id")),
        @AssociationOverride(name = "primaryKey.second", joinColumns = @JoinColumn(name = "code")) })
public class FirstsSeconds{

    @EmbeddedId
    private FirstsSecondsId primaryKey = new FirstsSecondsId();

    @Column(name = "extra", nullable = false)
    private String extra;

    ...
}

所以id类:

@Embeddable
public class FirstsSecondsId {

    @ManyToOne
    private First first;
    @ManyToOne
    private Second second;

    ...
}

最后,为了获得HQL结果,我创建了一个包含我想要的字段的新类: 公共类NewObject

public CargoOrder(String firstDescription, String fsExtra) {
    this.firstDescription = firstDescription;
    this.fsExtra = fsExtra;
}
...

首先,我想要第一个描述和FirstsSecond的额外内容,所以这是我的查询 JOIN fr.seconds as fs

@Query("SELECT new com.mypackage.NewObject("
        + "fr.description as firstDescription, fs.extra as fsExtra) "
        + "FROM First as fr"
        + "JOIN fr.seconds as fs")
public List<NewObject> findManyToMany();

但我没有结果:( ...在这种情况下我必须指定where条件?

@Query("SELECT new com.mypackage.NewObject("
        + "fr.description as firstDescription, fs.extra as fsExtra) "
        + "FROM First as fr"
        + "JOIN fr.seconds as fs WHERE fr.first = fs.primaryKey.first")
public List<NewObject> findManyToMany();

这不能在 JOIN fr.seconds上编译为fs WHERE fr.first = fs.primaryKey.first。 ..

亲切的问候。

1 个答案:

答案 0 :(得分:1)

已解决...在应用程序属性中使用spring.jpa.show_sql = true进行调试我发现在连接条件中存在错误匹配,我映射了错误的键:

在头等舱中primaryKey.first(不是第二个):

@OneToMany(mappedBy = "primaryKey.first")
private List<FirstsSeconds> seconds = new LinkedList<>();

在第二个primaryKey.second(不是第一个):

@OneToMany(mappedBy = "primaryKey.second")
private List<FirstsSeconds> firsts = new LinkedList<>();