软件编程
位置:首页>> 软件编程>> java编程>> 使用JPA自定义VO类型转换(EntityUtils工具类)

使用JPA自定义VO类型转换(EntityUtils工具类)

作者:不得真假  发布时间:2023-08-26 14:56:17 

标签:JPA,VO,类型转换,EntityUtils

JPA自定义VO类型转换(EntityUtils工具类)

在JPA查询中,如果需要返回自定义的类,可以使用EntityUtils工具类,该类源码:


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 954L
* @create 2019/10/30 17:27
*/
public class EntityUtils {

private static final Logger log = LoggerFactory.getLogger(EntityUtils.class);

/**
    * 将数组数据转换为实体类
    * 此处数组元素的顺序必须与实体类构造函数中的属性顺序一致
    *
    * @param list  数组对象集合
    * @param clazz 实体类
    * @param <T>   实体类
    * @param model 实例化的实体类
    * @return 实体类集合
    */
   public static <T> List<T> castEntity(List<Object[]> list, Class<T> clazz, Object model) {
       List<T> returnList = new ArrayList<T>();
       if (list.isEmpty()) return returnList;
       Object[] co = list.get(0);
       List<Map> attributeInfoList = getFiledsInfo(model);
       Class[] c2 = new Class[attributeInfoList.size()];
       if (attributeInfoList.size() != co.length) {
           return returnList;
       }
       for (int i = 0; i < attributeInfoList.size(); i++) {
           c2[i] = (Class) attributeInfoList.get(i).get("type");
       }
       try {
           for (Object[] o : list) {
               Constructor<T> constructor = clazz.getConstructor(c2);
               returnList.add(constructor.newInstance(o));
           }
       } catch (Exception ex) {
           log.error("实体数据转化为实体类发生异常:异常信息:{}", ex.getMessage());
           return returnList;
       }
       return returnList;
   }

private static Object getFieldValueByName(String fieldName, Object modle) {
       try {
           String firstLetter = fieldName.substring(0, 1).toUpperCase();
           String getter = "get" + firstLetter + fieldName.substring(1);
           Method method = modle.getClass().getMethod(getter, new Class[]{});
           Object value = method.invoke(modle, new Object[]{});
           return value;
       } catch (Exception e) {
           return null;
       }
   }

private static List<Map> getFiledsInfo(Object model) {
       Field[] fields = model.getClass().getDeclaredFields();
       List<Map> list = new ArrayList(fields.length);
       Map infoMap = null;
       for (int i = 0; i < fields.length; i++) {
           infoMap = new HashMap(3);
           infoMap.put("type", fields[i].getType());
           infoMap.put("name", fields[i].getName());
           infoMap.put("value", getFieldValueByName(fields[i].getName(), model));
           list.add(infoMap);
       }
       return list;
   }
}

使用原生sql查询:


   /**
    * 根据公司名称查询岗位
    * @param name 公司名称
    * @return  List<EmploymentPosition>
    */
   @Query(value = "select id, position, salary, people, experience, address, update_time from employment_position where company_name = ?1 and is_delete is false ORDER BY sort asc", nativeQuery = true)
   List<Object[]> findByCompanyName(String name);

使用类型转换:


@Override
   public List<EmploymentPositionVO> findByCompanyName(String name) {
       List<Object[]> objects = employmentPositionRepository.findByCompanyName(name);
       return EntityUtils.castEntity(objects, EmploymentPositionVO.class, new EmploymentPositionVO());
   }

VO类如下:


import lombok.Data;
import java.math.BigInteger;
import java.sql.Timestamp;

/**
* @website https://el-admin.vip
* @description /
* @author budezhenjia
* @date 2021-02-08
**/
@Data
public class EmploymentPositionVO {

/** ID */
   private BigInteger id;

/** 岗位名称 */
   private String position;

/** 月薪 */
   private String salary;

/** 人数 */
   private Integer people;

/** 工作经验 */
   private String experience;

/** 工作地点 */
   private String address;

/** 更新时间 */
   private Timestamp updateTime;
   public EmploymentPositionVO(BigInteger id, String position, String salary, Integer people, String experience, String address, Timestamp updateTime) {
       this.id = id;
       this.position = position;
       this.salary = salary;
       this.people = people;
       this.experience = experience;
       this.address = address;
       this.updateTime = updateTime;
   }
   public EmploymentPositionVO() {
   }
}

注意!

查询sql语句所查询出来的字段应与VO类中属性顺序一致,类型也需要一致!!

例如ID这个字段MySQL中类型为bigint,VO类中的类型为bigInteger

dto,vo,po,bo等实体转换工具类

3层开发以及不是多么新颖的开发思想了,但是呢,苦于开发的程序猿们,经常会被各个实例之间的转换弄得晕头转向,尤其是转换的次数多了,一下就蒙了,不知道转到哪里去了,博主也有这种困难,于是在网上到处找,找到了一些方法,并结合自身的开发使用,填补一些坑,希望对大家有所帮助!

下面宣布这次的主角:dozer

他是谁,一看英文名就不懂吧,其实他是一个大家都知道的一个角色,spring里面他可是家喻户晓的一个主角,没错就是beanUtils(其实,就是他的替身!)主要作用就是用来复制 JavaBean 属性的类库,什么叫复制,没错,就一模一样的再来一份,但是这样有一点点小小的区别,那就是,在使用的时候,需要指定一个“容器”(瞎说的,就是一个映射接受对象,也可以叫做目标)来存放,不然,复制到哪去,是不是。

这个时候呀,就有一个经纪人的出现,需要通过“经纪人”去代理复制,才能叫这个替身出来呀(专业替身30年,必须要有经纪人)


<dependency>
   <groupId>net.sf.dozer</groupId>
   <artifactId>dozer</artifactId>
   <version>5.5.1</version>
</dependency>

来源:https://blog.csdn.net/qq_34794527/article/details/114144034

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com