一尘不染

在Spring Data JPA中联接两个表实体

spring

我想写一个查询SELECT * FROM Release_date_type a LEFT JOIN cache_media b on a.id=b.id。我是Spring Data JPA的新手。我不知道如何为Join查询编写实体。这是一个尝试:

@Entity
@Table(name = "Release_date_type")
public class ReleaseDateType {

    @Id
    @GeneratedValue(strategy=GenerationType.TABLE)
    private Integer release_date_type_id;
    // ...
    @Column(nullable = true) 
    private Integer media_Id;
    // with getters and setters...
}

另一个实体是:

@Entity
@Table(name = "Cache_Media")
public class CacheMedia {

    @Id
    @GeneratedValue(strategy=GenerationType.TABLE)
    private Integer id;
    // ...
    private Date loadDate; //with the getter and setter ..
}

我想写一个crudRepository诸如

public interface ReleaseDateTypeRepository extends CrudRepository<ReleaseDateType, Long>{
    @Query("SELECT * FROM Release_date_type a LEFT JOIN cache_media b on a.id=b.id")
    public List<ReleaseDateType> FindAllWithDescriptionQuery();
}

阅读 673

收藏
2020-04-12

共1个答案

一尘不染

有关员工拥有一个或多个电话的典型示例,请参阅此Wikibook部分。

对于你的特定示例,如果你想建立one-to-one关系,则应更改ReleaseDateType模型中的下一个代码:

@Column(nullable = true) 
private Integer media_Id;

对于:

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="CACHE_MEDIA_ID", nullable=true)
private CacheMedia cacheMedia ;

在CacheMedia模型中,你需要添加:

@OneToOne(cascade=ALL, mappedBy="ReleaseDateType")
private ReleaseDateType releaseDateType;

然后应在你的存储库中替换:

@Query("Select * from A a  left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();

通过:

//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedia_Id(Integer id); 

或通过:

@Query("FROM ReleaseDateType AS rdt WHERE cm.rdt.cacheMedia.id = ?1")    //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);

或者,如果你喜欢使用@OneToManyand @ManyToOne关系,则应在ReleaseDateType模型中更改下一个代码:

@Column(nullable = true) 
private Integer media_Id;

对于:

@OneToMany(cascade=ALL, mappedBy="ReleaseDateType")
private List<CacheMedia> cacheMedias ;

在CacheMedia模型中,你需要添加:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="RELEASE_DATE_TYPE_ID", nullable=true)
private ReleaseDateType releaseDateType;

然后应在你的存储库中替换:

@Query("Select * from A a  left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();

通过:

//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedias_Id(Integer id); 

或通过:

@Query("FROM ReleaseDateType AS rdt LEFT JOIN rdt.cacheMedias AS cm WHERE cm.id = ?1")    //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);
2020-04-12