我的数据库中有 3 个表,REFD00
是用户,REFD01
是预订,REFD02
是连接表,一个预订有 N 个客人(用户)。我需要选择所有预订并获取所有客人。
表格: enter image description here
预订实体:
@Entity
@Table(name="REFD01")
public class Reserva implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="R1$COD", updatable=false)
private long codigo;
@Column(name="R1DATA")
private String data;
@Column(name="R1DESC")
private String descricao;
@Column(name="R1HORA")
private String hora;
@Column(name="R1USER")
private String criador;
//bi-directional many-to-many association to Utilizador
@ManyToMany
@JoinTable(
name="REFD02"
, joinColumns={
@JoinColumn(name="R2$RES")
}
, inverseJoinColumns={
@JoinColumn(name="R2$USR")
}
)
private List<Utilizador> refd00s;
用户:
@Entity
@Table(name="REFD00")
public class Utilizador implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="R0$COD", updatable=false)
private long codigo;
@Column(name="R0MAIL")
private String email;
@Column(name="R0NOME")
private String nome;
@Column(name="R0PASS")
private String password;
@Column(name="R0ROLE")
private String role;
@Column(name="R0USER")
private String username;
//bi-directional many-to-many association to Reserva
@ManyToMany(mappedBy="refd00s")
private List<Reserva> refd01s;
获取所有预订的方法:
List<Reserva> entitys = getRepositories().getReservaRepository().findAll();
结果是:
"codigo": 1,
"data": "2017-05-11",
"hora": "16:00",
"criador": "xpto",
"descricao": "Game",
"refd01s": null
如果您愿意使用左外连接获取
,那么您可以将@EntityGraph
配置添加到该接口(interface)方法:
@EntityGraph(attributePaths = { "refd00s" }, type = EntityGraphType.FETCH)
public List<Reserva> findAllWithGuests();
如果您使用了内部连接获取
,那么您必须在实体中添加急切的获取配置参数(您必须小心这一点):
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name="REFD02"
, joinColumns={
@JoinColumn(name="R2$RES")
}
, inverseJoinColumns={
@JoinColumn(name="R2$USR")
}
)
private List<Utilizador> refd00s;
或使用显式的@Query
定义:
@Query("select r from Reserva r inner join fetch r.refd00s")
public List<Reserva> findAllWithGuests();
我是一名优秀的程序员,十分优秀!