我如何找到所有内部联接

时间:2017-05-12 22:24:24

标签: java spring jpa spring-data spring-data-jpa

我的数据库中有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

1 个答案:

答案 0 :(得分:0)

如果您使用left outer join fetch,则可以将@EntityGraph配置添加到该接口方法:

@EntityGraph(attributePaths = { "refd00s" }, type = EntityGraphType.FETCH)
public List<Reserva> findAllWithGuests();

如果您使用inner join fetch,那么您必须在实体中添加急切的抓取配置参数(您必须小心):

@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();