我正在尝试在Spring Boot中使用QueryDSL,它工作得很好,直到我碰到一个我找不到答案的问题。假设我有以下结构:
+-------+ +----------+ +-------+
| foo | | foo_bar | | bar |
+-------+ +----------+ +-------+
| id | -------->| foo_id | +- | id |
| name | | bar_id |<------| | name |
+-------+ | position | +-------+
+----------+
我正在尝试使用QueryDSL中的Projections
来管理我的服务响应,因此我将类定义为:
让Foo.class
@Entity
@Table(name = "foo")
public class Foo{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 100)
private String name;
// Relations
@OneToMany(fetch = FetchType.LAZY, mappedBy = "foo")
private List<FooBar> fooBars;
// Getters and Setters
}
FooBar.class
@Entity
@Table(name = "foo_bar")
public class AlbumView{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private int position;
@ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinColumn(name = "foo_id")
private Foo foo;
@ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinColumn(name = "bar_id")
private Bar bar;
// Getters and Setters
}
Bar.class
@Entity
@Table(name = "bar")
public class Bar{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 100)
private String name;
// Relations
@OneToMany(fetch = FetchType.LAZY, mappedBy = "bar")
private List<FooBar> fooBars;
// Getters and Setters
}
现在在我的控制器中,我正在尝试执行以下代码,以Foo
返回FooBars
,其中Bar
id为1.查询类型有效,因为它仅返回Foo
id等于1的Bar
,但我不知道如何获取关系表中的position
属性。
JPQLQuery query = new JPAQuery(entityManager);
QFoo foo = QFoo.foo;
QFooBar fooBar = QFooBar.fooBar;
return query.from(foo)
.join(foo.fooBars, fooBar).on(fooBar.bar.id.eq((long)1))
.list(Projections.bean(Foo.class,
foo.id,
foo.name,
Projections.bean(FooBar.class,
???
// foo.fooBars.position can't be used because fooBars is an array
// foo.fooBars.get(0).position can't be used because i throws NullPointerException
).as("fooBars")
)
);
提前致谢。