废话不多说直接上代码
/**
* 将source的所有属性拷贝至target,source里没有的字段,target里不覆盖
* @param source
* @param target
* @return
*/
public static <U> void map(final Object source, final U target) {
DozerBeanMapper mapper = new DozerBeanMapper();
mapper.addMapping(new BeanMappingBuilder() {
@Override
protected void configure() {
mapping(source.getClass(), target.getClass(),
new TypeMappingOption[] {TypeMappingOptions.mapNull(false) });
}
});
mapper.map(source, target);
}
使用:DozerMapperUtil.map(entity, entityOld);
entity对象中有子对象集合
BoJob entityOld = this.findOne(entity.getJobUUID());
entityOld :使用jpa查询到的对象
原始实体类,子字段
@OneToMany(fetch=FetchType.LAZY)
@NotFound(action = NotFoundAction.IGNORE)
@Where(clause="isValid=1")
@JoinColumn(name = "jobUUID", referencedColumnName = "jobUUID",insertable = false, updatable = false)
public List<BoJobServer> getBoJobServerList() { return boJobServerList; }
public void setBoJobServerList(List<BoJobServer> boJobServerList) { this.boJobServerList = boJobServerList; }
测试代码
@Test
public void saveAllJpa(){
//模拟登陆用户
SysUser sysUser = new SysUser();
SysFramework sysFramework = new SysFramework();
sysFramework.setJobNoCode("SH");
sysUser.setBranchFramework(sysFramework);
sysUser.setUserId(60);
sysUser.setUserNameEn("cxy");
sysUser.setCreationTime("2012-12-12");
BoJob boJob = new BoJob();
boJob.setJobUUID("40288b8172275b3f0172275b66b50000");
boJob.setJobNoHead("66");
boJob.setJobType(2);
BoJobServer boJobServer = new BoJobServer();
// boJobServer.setJobServerUUID("4028728171634772017163a9cd140005");
ArrayList<BoJobServer> boJobServers = new ArrayList<>();
boJobServers.add(boJobServer);
boJob.setBoJobServerList(boJobServers);
BoJob boJob1 = boJobJpaService.saveAll(boJob, sysUser);
}
错误:
org.dozer.MappingException: java.lang.reflect.InvocationTargetException
debug模式下,子集合显示错误
Unable to evaluate the expression Method threw ‘org.hibernate.LazyInitializationException’ exception
修改方式为:把懒加载修改为及时加载
@OneToMany(fetch=FetchType.EAGER)
之后又报错:
cannot simultaneously fetch multiple bags
修改:添加 @Fetch(FetchMode.SUBSELECT)
大功告成:觉得对你有帮助,帮忙点个赞吧!