java 后臺開發(fā)中model與entity(實體類)的區(qū)別說明
以前在做項目的時候不太了解model與entity的含義,在公司(卓~)項目中學(xué)習(xí)到了。model的字段>entity的字段,并且model的字段屬性可以與entity不一致,model是用于前端頁面數(shù)據(jù)展示的,而entity則是與數(shù)據(jù)庫進(jìn)行交互做存儲用途。
舉個例子:
比如在存儲時間的類型時,數(shù)據(jù)庫中存的是datetime類型,entity獲取時的類型是Date()類型,date型的數(shù)據(jù)在前端展示的時候必須進(jìn)行類型轉(zhuǎn)換(轉(zhuǎn)為String類型),在前端的進(jìn)行類型轉(zhuǎn)換則十分的麻煩,轉(zhuǎn)換成功了代碼也顯得十分的臃腫,
所以將entity類型轉(zhuǎn)換后,存儲到對應(yīng)的model中,在后臺做類型轉(zhuǎn)換,然后將model傳到前端顯示時,前端的就十分的干凈。
同時也可以添加字段,作為數(shù)據(jù)中轉(zhuǎn)。
具體的轉(zhuǎn)換思路,還沒具體看是怎么處理的,等后面看了補(bǔ)上。
補(bǔ)充知識:java 使用反射在dto和entity 實體類之間進(jìn)行轉(zhuǎn)換
public class Utils {/*** 將dto和entity之間的屬性互相轉(zhuǎn)換,dto中屬性一般為String等基本類型,* 但是entity中可能有復(fù)合主鍵等復(fù)雜類型,需要注意同名問題* @param src* @param target*/public static Object populate(Object src, Object target) {Method[] srcMethods = src.getClass().getMethods();Method[] targetMethods = target.getClass().getMethods();for (Method m : srcMethods) {String srcName = m.getName();if (srcName.startsWith('get')) {try {Object result = m.invoke(src);for (Method mm : targetMethods) {String targetName = mm.getName();if (targetName.startsWith('set') && targetName.substring(3, targetName.length()).equals(srcName.substring(3, srcName.length()))) {mm.invoke(target, result);}}} catch (Exception e) { }}}return target;}/*** dto集合和實體類集合間的互相屬性映射* @param src* @param target* @param targetClass* @return*/@SuppressWarnings('unchecked')public static <S,T> List<T> populateList(List<S> src,List<T> target,Class<?> targetClass){for(int i = 0;i<src.size();i++){try {Object object = targetClass.newInstance();target.add((T) object);populate(src.get(i),object); } catch (Exception e) {continue;//某個方法反射異常} }return target;}}
以上這篇java 后臺開發(fā)中model與entity(實體類)的區(qū)別說明就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP.NET MVC遍歷驗證ModelState的錯誤信息2. JavaScript實現(xiàn)組件化和模塊化方法詳解3. .Net Core和RabbitMQ限制循環(huán)消費的方法4. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向5. ASP中if語句、select 、while循環(huán)的使用方法6. asp中response.write("中文")或者js中文亂碼問題7. jsp網(wǎng)頁實現(xiàn)貪吃蛇小游戲8. PHP設(shè)計模式中工廠模式深入詳解9. 刪除docker里建立容器的操作方法10. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明
