簡體   English   中英

在沒有 JPQL 的情況下連接兩個表

[英]Joining two tables without JPQL

我必須 MySQL 表 TICKET-是父級,USER-是子級,多對一關系。

=TICKET=
PK(ID)
summary
message
FK(user_id) references USER(user_id)

=USER=
PK(ID)
email
password

和 JPA 實體

@Entity 
class TICKET {
    @Id
    private Integer ID;
    private String summary;
    private String message;
    @ManyToOne
    @JoinColumn(name="user")
    private USER user;
}

@Entity
class USER {
    @Id
    private Integer ID;
    private String email;
    private String password;
}

如果我通過 ID 進行查詢以獲取票證,它還將返回不好的用戶信息(USER.ID、USER.email、USER.password)。

ticketsCrudRepository.findById(ticketId);

我想要的是得到一個看起來像這樣的表:

TICKET.ID | summary | message | USER.email

我知道如何在 MySQL 中做到這一點,但 JPA 這對我來說太重要了。 我不想使用 JPQL 或本地查詢語言。 有什么建議么?

當您獲取 Ticket 時,您還會得到一個 User,因為@ManyToOne默認具有FetchType.EAGER 您可以通過將注釋更改為@ManyToOne(fetch = FetchType.LAZY)

要進行搜索,您可以嘗試類似

public List<Object[]> getTikcetsForUser(final User user) {
   String hql = "select t.id, t.summary, t.message, u.email "
                + "from Tikcet t, User u "
                + "where ticket.user = :user";

   Query<Object[]> query = getSession().createQuery(hql, Object[].class);
   query.setParameter("user", user);
   return query.getResultList();
}

返回的列表將包含 arrays 和 4 個字段(t.id、t.summary、t.message、u.email)。

如果您覺得這很有用,請告訴我。

:)

我正在尋找的解決方案是 Spring 數據 JPA 預測。 它們可以是具有與您要從數據庫中獲取的列相匹配的 getter 的接口或類。 有關詳細信息,請在此處查看 Spring 框架文檔。

使用 Spring 數據投影是一種選擇,但您有時會遇到它的限制。 如果您達到了這一點,您可以查看Blaze-Persistence Entity Views

我創建了該庫以允許在 JPA 模型和自定義接口或抽象 class 定義的模型之間輕松映射,例如 Spring 類固醇上的數據投影。 這個想法是您以您喜歡的方式定義您的目標結構(域模型),並通過 JPQL 表達式將 map 屬性(吸氣劑)定義為實體 model。

使用 Blaze-Persistence Entity-Views 的 DTO model 可能如下所示:

@EntityView(TICKET.class)
public interface TicketDto {
    @IdMapping
    Long getId();
    String getName();
    UserDto getUser();

    @EntityView(USER.class)
    interface UserDto {
        @IdMapping
        Long getId();
        String getEmail();
    }
}

或者在你的情況下更簡單

@EntityView(TICKET.class)
public interface TicketDto {
    @IdMapping
    Long getId();
    String getName();
    @Mapping("user.email")
    String getUserEmail();
}

查詢是將實體視圖應用於查詢的問題,最簡單的就是通過 id 進行查詢。

TicketDto a = entityViewManager.find(entityManager, TicketDto.class, id);

Spring 數據集成讓您幾乎可以像 Spring 數據投影一樣使用它: https://persistence.blazebit.com/documentation/entity-view/manual-html/。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM