JPA使用之@Query的常用寫法


准備

實體

@Data
@Table(name = "task_apply")
@Entity
public class TaskApply {
    @Id
    @GeneratedValue
    @Column(name = "apply_id")
    private Long applyId;
    
    private Integer status;
    
    private SyncType type;
    
    @Column(name = "task_message")
    private String taskMessage;
}

其中同步類型

package com.charles.enums

public enum SyncType {
    /**
     * 手動同步
     */
    MANUAL("M", "手動同步"),
    /**
     * 任務同步
     */
    SCHEDULED("S", "任務同步");

    private final String value;
    private final String text;

    SyncType(String value, String text) {
        this.value = value;
        this.text = text;
    }

    public String text() {
        return text;
    }

    public String getValue() {
        return value;
    }

    public static SyncType fromValue(String type) {
        for (SyncType value : SyncType.values()) {
            if (value.equals(type)) {
                return value;
            }
        }
        return null;
    }
}

枚舉的轉換器

import javax.persistence.AttributeConverter;

public class SyncTypeConverter implements AttributeConverter<SyncType, String> {

    @Override
    public String convertToDatabaseColumn(SyncType e) {
        if (e == null) {
            return null;
        }
        return e.getValue();
    }

    @Override
    public SyncType convertToEntityAttribute(String value) {
        if (value == null) {
            return null;
        }
        return SyncType.fromValue(value);
    }
}

修改

使用冒號傳參

@Modifying
@Query("update TaskApply set status = :status where applyId = :applyId")
void updateStatusByApplyId(@Param("applyId") Long applyId, @Param("status") Integer status);

使用問號傳參

@Modifying
@Query("update TaskApply set status = ?2 where applyId = ?1")
void updateStatusByApplyId(Long applyId, Integer status);

查詢

返回指定列第1種寫法

package com.charles.vo;

@Data
public class TaskMessageVO {
    private Long applyId;
    private String taskMessage;
}

@Query("select new com.charles.vo.TaskMessageVO(applyId, taskMessage) from TaskApply where applyId in (:applyIds)")
List<TaskMessageVO> findTaskMessages(@Param("applyIds") List<Long> applyIds);

返回指定列第2種寫法

@Query(nativeQuery = true, value = 
"SELECT id as applyId, task_message as taskMessage FROM task_apply WHERE apply_id IN (:applyIds)")
List<Object> findTaskMessages(@Param("applyIds") List<Long> applyIds);

這種寫法是nativeQuery,返回的結果中每個Object中返回的是一個數組,數組下標0對應的是applyId,下標1對應的是taskMessage。

查詢單列

@Query("select distinct status from TaskApply where applyId in (:applyIds)")
List<Integer> findDistinctStatus(@Param("applyIds") List<Long> applyIds);

查詢條件為常量

@Query("select applyId from TaskApply where type <> com.charles.enums.SyncType.MANUAL")
List<Long> findNotManualSyncApplyIds();

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM