1. 程式人生 > 實用技巧 >jpa轉json問題

jpa轉json問題

1.因為hibernate有些返回的是hibernateProxy物件,該物件會延遲載入資料. 當資料庫不存在指定資料時,延遲載入會丟擲異EntityNotFoundException,於是在springboot幫我返回json資料前把hibernateProxy執行toString,捕獲EntityNotFoundException進行個性化返回

public class JsonResult<T> {
	
	private int code; //錯誤碼
	private String msg; //錯誤資訊
	private T data; //返回的資料
	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public T getData() {
		return data;
	}
	public void setData(T data) {
		this.data = data;
	}
	
	public static JsonResult successResult(Object obj) {
		JsonResult result = new JsonResult();
		if(obj instanceof HibernateProxy) {
			try {
				System.out.println(obj.toString()); // 如果hibernateProxy代理物件在資料庫中不存在toString就拋異常
			} catch (EntityNotFoundException e) {
				result.setCode(998);
				result.setMsg("物件不存在!");
				result.setData(null);
				return result;
			}
		}
		result.setCode(0);
		result.setMsg("成功");
		result.setData(obj);
		return result;
	} 
	
	public static JsonResult errorResult(int code,String message) {
		JsonResult result = new JsonResult();
		result.setCode(code);
		result.setMsg(message);
		return result;
	}
	
	public static JsonResult errorResult(MsgEnum em) {
		JsonResult result = new JsonResult();
		result.setCode(em.getCode());
		result.setMsg(em.getMessage());
		return result;
	}
	
}

 2.為了json只返回指定的欄位,其他不需要的資訊不返回,定義一個指明欄位的返回類, 返回通過spring提供的beanUtil.copyProperties進行復制,為了方便list複雜,定義一個工具類

public class CopyUtil extends BeanUtils {

	public static <S, T> List<T> copyList(List<S> sources, List<T> targets) {

		if (sources == null || sources.size() == 0) return null;
		List<T> ts = new ArrayList<T>();
		int i = 0;
		for (S s : sources) {
			T t = targets.get(i);
			copyProperties(s, t);
			ts.add(t);
			i++;
		}
		return ts;
	}
}

  3.呼叫:

List<Article> articles =  articleService.getArticles(start,limit).getContent();
	    List<ArticleSerializer> ass = new ArrayList<ArticleSerializer>(Collections.nCopies(articles.size(), new ArticleSerializer()));
	    CopyUtil.copyList(articles, ass);
	    return JsonResult.successResult(ass);