Spring Boot Jpa 獲取數據庫中對應的結果集

在很多時候,我們並不是想要查詢到數據庫中所有的列內容,而是中間特定的列對應的內容,使用Spring boot Jpa實現這類查詢需要下面的步驟:

首先需要一個實體類, 比如

@Table(name = "LoginLog")
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class LoginLog {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name = "id", columnDefinition = "bigint", nullable = false, unique = true)
    Long id;

    @Column(name = "userId", columnDefinition = "bigint")
    Long userId;

   @Column(name = "ip", columnDefinition = "varchar(20)", nullable = false)
    String ip;

   @Column(name = "address", columnDefinition = "varchar(50)")
    String address;

   @Column(name = "create_time", columnDefinition = "datetime default now()")
    String create_time;

}

上面對應的信息有id, userId, ip, address, create_time, 如果我只想要ip, address, create_time, 那麼我需要重新定義一個接口, 接口中間是實體類對應的getter!!

public interface LoginLogInfo {
    /*
    自定義查詢結果集 獲取用戶的登錄日誌
     */
     String getIp();

     String getAddress();

     String getCreate_time();

}

定義好這個接口之後,我們可以直接以返回類型的形式使用這個接口

@Query(value = "SELECT ip, address, create_time FROM login_log WHERE user_id=:user_id", nativeQuery = true)
List<LoginLogInfo> findAllByUserId(@Param("user_id") Long user_id);

這樣返回的結果就是我們需要的內容了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章