如何在OneToMany映射中的Java Hibernate中设置查询参数?

时间:2018-11-30 15:43:14

标签: java postgresql hibernate orm

我有一个问题: 我有3个班级和3个桌子:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "VehiclesBodies")
public class VehicleBody {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "vehicleBodyId")
    private Long vehicleBodyId;

    @JoinColumn(name = "trunk")
    private int trunk;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "vehicleModelId")
    private VehicleModel vehicleModel;

    @OnDelete(action = OnDeleteAction.CASCADE)
    @OneToMany(mappedBy = "vehicleBody")
    private List<VehicleDrive> vehicleDrives = new ArrayList<>();
}


@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "VehiclesDrives")
public class VehicleDrive {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "vehicleDriveId")
    private Long vehicleDriveId;

    @JoinColumn(name = "engine")
    private double engine;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "vehicleBodyId")
    private VehicleBody vehicleBody;

    @ManyToOne//(fetch = FetchType.LAZY)
    @JoinColumn(name = "dictionaryCarDriveId")
    private DictionaryCarDrive dictionaryCarDrive;
}


@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "DictionaryCarDrives")
public class DictionaryCarDrive {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JoinColumn(name = "dictionaryCarDriveId")
    private Long dictionaryCarDriveId;

    @JoinColumn(name = "name")
    private String name;

    @OneToMany(mappedBy = "dictionaryCarDrive")
    private List<VehicleDrive> vehicleDrives = new ArrayList<>();
}

我想从数据库中仅获取具有柴油发动机的模型,并且VehicleDrives列表中的每个模型均仅包含柴油发动机。

List<VehicleBody> vehicleBodies = em.createQuery(
        "Select distinct b from VehicleBody b " +
        "join b.vehicleDrives d " +
        "join d.dictionaryCarDrive c " +
        "where c.name=:name ", VehicleBody.class).
    setParameter("name", "Diesel").
    getResultList();

当前,该列表包括具有柴油发动机但不仅包含这些发动机(还有汽油发动机)的模型。我想在VehicleDrives列表中使用柴油发动机。我结合了join fetch,但没有任何帮助。我使用postgres。

0 个答案:

没有答案