首页 > 解决方案 > 为 CrudRepository (findById) 的一种方法返回两种不同的数据类型

问题描述

我正在使用 CrudRepository。

我在两种情况下需要方法 findById:

  1. EmailShort findById(Long id);
  2. EmailFull findById(Long id);

EmailShort 和 EmailFull 是接口。

public interface EmailFull extends EmailCustom {
    Long getId();

    UserShort getSender();
    String getContent();
    String getTopic();
    String getShortContent();

    @JsonFormat
            (shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
    Date getCreationTime();
}

public interface EmailShort extends EmailCustom {
    Long getId();

    UserShort getSender();
    String getTopic();
    String getShortContent();
    boolean getIsRead();
    void setRead(boolean read);

    @JsonFormat
            (shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
    Date getCreationTime();
}

我的仓库:

@Repository
public interface EmailDao extends CrudRepository<Email, Long> {

    EmailShort findById(Long id);

    @Query("select e from email e where e.id=?1")
    EmailFull findFullById(@Param("id") Long id);

    @Query(value = "select * " +
            "from email " +
            "where email.id = :emailId", nativeQuery = true)
    EmailShort findByIdWithShortSenderInfo(@Param("emailId") long emailId);
}

我不能使用电子邮件对象,因为它包含带有地址等数据的用户(不需要它)。

任何想法如何解决这个问题?Maybie 我应该更改实体定义吗?

标签: springspring-data

解决方案



推荐阅读