前言
今天用JPA又把之前的防疫物資項目重構(gòu)了一遍哼御,遇到很多問題坯临,不過最終都解決了,JPA的學習之路還是很長...
遇到難題
1.聯(lián)表查詢(返回自定義實體類)
JPA確實很強大恋昼,簡單的CRUD用的簡直舒服~看靠,但是今天在使用聯(lián)表查詢的時候,遇到了很棘手的問題液肌。直接上代碼挟炬。
@Entity
@Table(name = "material_record_info",)
public class MaterialRecordDO implements Serializable {
private static final long serialVersionUID = 1642587292218800992L;
private int recordId;
private Integer receiveNumber;
private String receiveReason;
private Date receiveDateTime;
private int mId;
private int uId;
get/set方法我就省略了,這是外鍵表物資記錄表嗦哆,其中的mId和uId是另外兩張表的主鍵谤祖。但是最終想顯示給用戶的這樣的:
public class MaterialRecordVO {
private int recordId; //記錄編號
private int receiveNumber; // 領(lǐng)取數(shù)量
private String receiveReason; //領(lǐng)取原因
private Date receiveDateTime; //領(lǐng)取時間
private String materialName; //防疫物資名稱
private String userRealName; //用戶真實姓名
最終使用JPQL解決了問題,注意自定義實體類要有對應(yīng)的有參構(gòu)造函數(shù)吝秕,順序也必須一樣泊脐。
@Repository
public interface IMaterialRecordDAO extends JpaRepository<MaterialRecordDO, Integer> {
@Query("SELECT new co'm.apesource.epmrs_3.entity.MaterialRecordVO(a.recordId,a.receiveNumber,a.receiveReason,a.receiveDateTime,b.materialName,c.userRealName)" +
"FROM MaterialRecordDO a " +
"INNER JOIN MaterialInfo b ON a.mId = b.materialId" +
"INNER JOIN UserInfo c ON a.uId = c.userId")
List<MaterialRecordVO> listMaterialRecord();
2.聯(lián)表動態(tài)查詢(返回自定義實體類)
我看了看JpaspecificationExecutor實現(xiàn)動態(tài)查詢的,看不太懂烁峭,而且好像不能返回自定義實體類容客,搞了幾個小時秕铛,最終還是用MyBatis解決了(太香了...),一個項目既用MyBatis又用JPA是不是不好呢缩挑。但两。。
// 按條件查詢物資領(lǐng)用記錄
@Select("<script> " +
"SELECT record_id AS recordId,\n" +
" material_name AS materialName,\n" +
" user_real_name AS userRealName,\n" +
" receive_number AS receiveNumber,\n" +
" receive_reason AS receiveReason,\n" +
" receive_date_time AS receiveDateTime\n" +
" FROM material_record_info AS a\n" +
" INNER JOIN material_info AS b ON a.m_id = b.material_id\n" +
" INNER JOIN user_info AS c ON a.u_id = c.user_id\n" +
" <where>\n" +
" <if test='materialId != -1'>AND material_id = #{materialId}</if>\n" +
" <if test='userId != -1'>AND user_id = #{userId}</if>\n" +
" <if test='receiveDateBegin != null and receiveDateEnd != null'>\n" +
" AND DATE_FORMAT(receive_date_time,'%Y-%m-%d') BETWEEN #{receiveDateBegin} AND #{receiveDateEnd}\n" +
" </if>\n" +
" </where>\n" +
" ORDER BY receive_date_time" +
"</script> ")
List<MaterialRecordVO> listMaterialRecordByCondition(MaterialRecordCondition recordCondition);
用這個記得加個<script>標簽供置,不然不能解析谨湘,很怪。
總結(jié)
剛剛上手使用SpringBoot重構(gòu)項目之后芥丧,會有一些面試相關(guān)的問題吧
1.使用Spring框架的好處
2.注解怎么使用或者原理
3.Spring怎么實現(xiàn)Bean的管理的
4.Spring容器初始化過程
5.IOC思想
這些東西明天再做一個整理紧阔。