javabean实体类与实体类之间的快速转换
生活随笔
收集整理的這篇文章主要介紹了
javabean实体类与实体类之间的快速转换
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、Dozer是什么?
dozer是一個(gè)能把實(shí)體和實(shí)體之間進(jìn)行轉(zhuǎn)換的工具.只要建立好映射關(guān)系.就像是ORM的數(shù)據(jù)庫和實(shí)體映射一樣.
使用方法示例如下:
// article(PO) -> articleVOArticleVO articleVO = dozerMapper.map(article, ArticleVO.class);
這段示例代碼。將從數(shù)據(jù)庫里面查詢得到的PO對(duì)象article,轉(zhuǎn)換為VO對(duì)象articleVO,轉(zhuǎn)換過程將所有同名同類型的數(shù)據(jù)自動(dòng)賦值給articleVO的成員變量,當(dāng)然除了reader(因?yàn)镻O里面沒有reader數(shù)組數(shù)據(jù))。轉(zhuǎn)換需要寫屬性之間的映射么?不! 默認(rèn)是根據(jù)屬性名稱來匹配的.
如果沒有Dozer我們進(jìn)行,對(duì)象之間的轉(zhuǎn)換賦值,我們會(huì)怎么做?下面的這5行等于上面的一行。
articleVO.setId(article.getId());
articleVO.setAuthor(article.getAuthor());
articleVO.setTitle(article.getTitle());
articleVO.setContent(article.getContent());
articleVO.setCreateTime(article.getCreateTime());
二、使用Dozer進(jìn)行實(shí)體類的轉(zhuǎn)換:
首先引入依賴
<dependency><groupId>net.sf.dozer</groupId><artifactId>dozer</artifactId><version>5.4.0</version></dependency>
注入一個(gè)工具類DozerBeanMapper 到上下文中,
@Configurationpublic class DozerBeanMapperConfigure {@Beanpublic DozerBeanMapper mapper() {DozerBeanMapper mapper = new DozerBeanMapper();return mapper;}}
注入然后開始使用啦
@Autowiredprotected Mapper dozerMapper;
在實(shí)際應(yīng)用中,我們不只需要PO轉(zhuǎn)VO,有時(shí)還需要List轉(zhuǎn)List.寫一個(gè)工具類,實(shí)現(xiàn)List轉(zhuǎn)List
public class DozerUtils {static DozerBeanMapper dozerBeanMapper = new DozerBeanMapper();public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass){List destinationList = Lists.newArrayList();for (Iterator i$ = sourceList.iterator(); i$.hasNext();){Object sourceObject = i$.next();Object destinationObject = dozerBeanMapper.map(sourceObject, destinationClass);destinationList.add(destinationObject);}return destinationList;}
}
以上!
總結(jié)
以上是生活随笔為你收集整理的javabean实体类与实体类之间的快速转换的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Maven安装与配置(最实用!!!)ec
- 下一篇: Spring Boot整合Spring