利用Java實(shí)體bean對(duì)象批量數(shù)據(jù)傳輸處理方案小結(jié)
javaBean在MVC設(shè)計(jì)模型中是model,又稱模型層,在一般的程序中,我們稱它為數(shù)據(jù)層,就是用來設(shè)置數(shù)據(jù)的屬性和一些行為,然后我會(huì)提供獲取屬性和設(shè)置屬性的get/set方法JavaBean是一種JAVA語言寫成的可重用組件。為寫成JavaBean,類必須是具體的和公共的,并且具有無參數(shù)的構(gòu)造器。
下面通過本文給大家分享利用Java實(shí)體bean對(duì)象批量數(shù)據(jù)傳輸處理的解決方案。
需求
現(xiàn)在有兩方數(shù)據(jù)庫(kù)表結(jié)構(gòu)相同,一方A、另一個(gè)方B,現(xiàn)想從A處查詢出多個(gè)表的數(shù)據(jù),傳輸?shù)紹地保存起來。
解決方案1
最簡(jiǎn)單粗暴的方法就是,查詢出A處相關(guān)表的數(shù)據(jù)封裝到實(shí)體對(duì)象中,之后放到List集合中,再傳遞給B處,B處再遍歷集合,將數(shù)據(jù)保存到B處。但是此處的問題是想要再添加一個(gè)表的數(shù)據(jù)時(shí),需要改查詢的代碼還需要改保存的代碼,非常麻煩,所以不建議使用。
方案2
新建一個(gè)需要準(zhǔn)備哪些數(shù)據(jù)的實(shí)體類對(duì)象
待查詢的貓
@Data @AllArgsConstructor @NoArgsConstructor public class Cat { private String id; private String food; private String weight; private String height; }
待查詢的狗
@Data @AllArgsConstructor public class Dog { private String id; private String food; private String weight; private String height; }
待查詢的豬
@Data @AllArgsConstructor public class Pig { private String id; private String food; private String weight; private String height; private String pid; }
自定義傳輸實(shí)體對(duì)象,這里定義了需要查詢那些集合對(duì)象
@Data @AllArgsConstructor @NoArgsConstructor public class CustomDataTransferDTO{ /** * =============================================================== * 數(shù)據(jù)查詢結(jié)果 * =============================================================== */ /** * 待查詢的貓信息 */ private List<Cat> catList; /** * 待查詢的狗信息 通過注解來明確關(guān)聯(lián)關(guān)系 */ @CustomAnnotation.connectTable(tablePath = "com.study.customdatatransfer.Pig") private List<Dog> dogList; /** * 待查詢的豬信息 */ @Ignore private List<Pig> pigList;
2,新建參數(shù)關(guān)系類
公共參數(shù)關(guān)系類
/** * 這里為共通參數(shù)信息設(shè)置 * @author jieya */ @Data @AllArgsConstructor @NoArgsConstructor public class CommonParameterDTO { /** * =============================================================== * 這里配置所有集合查詢的公共查詢條件 * =============================================================== */ /** * 主鍵信息 */ public String id; }
自定義查詢參數(shù)
/** * 自定義查詢條件及關(guān)聯(lián)表信息查詢實(shí)體對(duì)象 * @author Administrator */ @Data @AllArgsConstructor @NoArgsConstructor public class TableAndParamsDTO { /** * 主表名 這里是查詢那個(gè)實(shí)體對(duì)象的數(shù)據(jù),這里的table值一定要和CustomDataTransferDTO中的List的泛型對(duì)上 */ @CustomAnnotation.Table private String table; /** * =============================================================== * 自定義參數(shù) * =============================================================== */ /** * 自定義查詢參數(shù) search 標(biāo)記這是一個(gè)查詢參數(shù) */ @CustomAnnotation.search private String food; /** * connectSearchTerm(term = "id") 這個(gè)標(biāo)記為這是連表查詢的副表,主表的id等于副表的pid */ @CustomAnnotation.connectSearchTerm(term = "id") private String pid; }
新建自定義處理主方法
/** * 自定義數(shù)據(jù)處理主方法 * * @author Administrator */ public class CustomDataMain { private static final List<Cat> catList = new ArrayList<>(); private static final List<Dog> dogList = new ArrayList<>(); private static final List<Pig> pigList = new ArrayList<>(); private static List<TableAndParamsDTO> tableAndParamsList = new ArrayList(); private static CommonParameterDTO commonParameter = new CommonParameterDTO(); static { catList.add(new Cat("1", "面包1", "10", "12")); catList.add(new Cat("2", "面包2", "10", "12")); catList.add(new Cat("3", "面包3", "10", "12")); catList.add(new Cat("4", "面包4", "10", "12")); dogList.add(new Dog("1", "米飯1", "10", "12")); dogList.add(new Dog("2", "米飯2", "10", "12")); dogList.add(new Dog("3", "米飯3", "10", "12")); dogList.add(new Dog("4", "米飯4", "10", "12")); pigList.add(new Pig("1", "麻辣燙1", "10", "12", "1")); pigList.add(new Pig("2", "麻辣燙2", "10", "12", "2")); pigList.add(new Pig("3", "麻辣燙3", "10", "12", "3")); pigList.add(new Pig("4", "麻辣燙4", "10", "12", "4")); } public static void main(String[] args) throws Exception { // 共通參數(shù) commonParameter.setId("1"); // TableAndParamsDTO tableAndParamsDTO = new TableAndParamsDTO(); tableAndParamsDTO.setTable("Pig"); tableAndParamsDTO.setFood("麻辣燙1"); tableAndParamsDTO.setPid("id"); tableAndParamsList.add(tableAndParamsDTO); findCustomData(CustomDataTransferDTO.class); } public static Object findCustomData(Class<?> clazz) throws Exception { // 實(shí)例化數(shù)據(jù)傳輸類 Object obj = clazz.newInstance(); // 首先得到pojo所定義的字段 Field[] fields = clazz.getDeclaredFields(); for (Field curField : fields) { // 設(shè)置字段可訪問(必須,否則報(bào)錯(cuò)) curField.setAccessible(true); // 如果 if (!curField.isAnnotationPresent(Ignore.class)) { CustomAnnotation.connectTable annotation = curField.getAnnotation(CustomAnnotation.connectTable.class); String sideTablePath = null; if (annotation != null) { sideTablePath = annotation.tablePath(); } Class<?> curFieldType = curField.getType(); // 集合List元素 if (curFieldType.equals(List.class)) { // 當(dāng)前集合的泛型類型 Type genericType = curField.getGenericType(); if (null == genericType) { continue; } if (genericType instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) genericType; // 得到泛型里的class類型對(duì)象 Class<?> actualTypeArgument = (Class<?>) pt.getActualTypeArguments()[0]; // 獲取完整路徑信息 String tablePath = actualTypeArgument.getName(); // 獲取實(shí)體對(duì)象名稱 String tableName = actualTypeArgument.getSimpleName(); // 獲取該實(shí)體對(duì)象設(shè)置的自定義信息 TableAndParamsDTO tableAndParams = tableAndParamsList.stream().filter(o -> o.getTable().equals(tableName)).findAny().orElse(null); // 拼接hql和執(zhí)行獲取數(shù)據(jù) obj = connectSqlAndExexute(obj, clazz, tablePath, tableAndParams, sideTablePath); } } else { System.out.println(curField.getName() + "--暫不支持的類型--" + curFieldType.getSimpleName()); } } else { System.out.println("Ignore----"); } } return null; } /** * 連接sql并獲取數(shù)據(jù) * * @param obj * @param clazz * @param tablePath * @param tableAndParams * @param sideTablePath * @return * @throws Exception */ private static Object connectSqlAndExexute(Object obj, Class<?> clazz, String tablePath, TableAndParamsDTO tableAndParams, String sideTablePath) throws Exception { int lastIndex = tablePath.lastIndexOf("."); String tableName = tablePath.substring(lastIndex + 1); List<Object> param = new ArrayList<>(); // 查詢語句 StringBuilder selectBuilder = new StringBuilder(" select * from " + tableName + " where 1=1"); // 查詢條件 StringBuilder whereBuilder = new StringBuilder(); // 拼接共通參數(shù) if (commonParameter != null) { // 拼接共通參數(shù) Field[] fields = commonParameter.getClass().getDeclaredFields(); for (Field curField : fields) { // 設(shè)置字段可訪問(必須,否則報(bào)錯(cuò)) curField.setAccessible(true); String name = curField.getName(); whereBuilder.append(" and " + name + "=?"); Object vlaue = ReflectionUtil.getVlaue(commonParameter, name, ""); param.add(vlaue); } } // 如果設(shè)置了表和特殊參數(shù)則按照特殊情況處理,否則使用共通參數(shù)拼接條件 if (tableAndParams != null) { // 遍歷該實(shí)體對(duì)象設(shè)置的配置信息 // 獲取主表 String table = tableAndParams.getTable(); // 拼接自定義經(jīng)營(yíng)范圍 Field[] fields = tableAndParams.getClass().getDeclaredFields(); for (Field field : fields) { // 判斷是否為查詢條件 if (field.isAnnotationPresent(CustomAnnotation.search.class)) { whereBuilder.append(" and " + field.getName() + "=?"); Object vlaue = ReflectionUtil.getVlaue(tableAndParams, field.getName(), ""); param.add(vlaue); } // 關(guān)聯(lián)查詢 if (field.isAnnotationPresent(CustomAnnotation.connectSearchTerm.class)) { String name = field.getName(); String values = GsUtils.blankNull(ReflectionUtil.getVlaue(tableAndParams, name, "")); String[] split = values.split(","); String sideWhere = ""; for (int i = 0; i < split.length; i++) { sideWhere += " and " + name + " in("; sideWhere += "'" + split[i] + "'" + ","; } ; sideWhere = sideWhere.substring(0, sideWhere.length() - 1); sideWhere += " )"; whereBuilder.append(sideWhere); } } } // 獲取查詢對(duì)象的class對(duì)象 Class tableClazz = Class.forName(tablePath); // hql不為空和hql中不包含and符號(hào)時(shí),禁止執(zhí)行sql,防止全庫(kù)掃描 if (StringUtils.isEmpty(whereBuilder.toString())) { throw new Exception("hql錯(cuò)誤,因不存在and查詢條件,會(huì)導(dǎo)致全庫(kù)掃描" + selectBuilder.toString()); } // TODO 執(zhí)行sql 將查詢到數(shù)據(jù)封裝到list<bean>對(duì)象中 // List list = baseDao.findByHql(selectBuilder.toString()+whereBuilder.toString(),tableClazz,param); // TODO 這段代碼為無用的為獲取數(shù)據(jù)的代碼 List list = findDataInfo(tableName,whereBuilder,param); // 將查詢到的信息添加到傳輸文件實(shí)體對(duì)象中 if (list != null && list.size() > 0) { obj = ReflectionUtil.setValue(obj, clazz, tableName, list); } // 連表查詢 if (sideTablePath != null) { String sideTableName = Class.forName(sideTablePath).getSimpleName(); // 獲取該實(shí)體對(duì)象設(shè)置的自定義信息 TableAndParamsDTO sideTableAndParams = tableAndParamsList.stream().filter(o -> o.getTable().equals(sideTableName)).findAny().orElse(null); // 拼接自定義經(jīng)營(yíng)范圍 Field[] sideFields = sideTableAndParams.getClass().getDeclaredFields(); for (Field field : sideFields) { // 關(guān)聯(lián)查詢 if (field.isAnnotationPresent(CustomAnnotation.connectSearchTerm.class)) { String term = field.getAnnotation(CustomAnnotation.connectSearchTerm.class).term(); String sideParam = ""; for (Object obj1 : list) { Object value = ReflectionUtil.getVlaue(obj1, (String) term, ""); if (value != null) { sideParam += value + ","; } } if (StringUtils.isEmpty(sideParam)) { throw new Exception("關(guān)聯(lián)表但為獲取到關(guān)聯(lián)條件信息" + selectBuilder.toString()); } // 將值設(shè)置到對(duì)象中 field.setAccessible(true); field.set(sideTableAndParams, sideParam); } } // 拼接hql和執(zhí)行獲取數(shù)據(jù) obj = connectSqlAndExexute(obj, clazz, sideTablePath, sideTableAndParams, null); } System.out.println("tableAndParams:" + tableAndParams + "commonParams:" + commonParameter + "執(zhí)行sql語句:" + selectBuilder.toString() + whereBuilder.toString() + "查詢條件:" + param + "查詢結(jié)果:" + list); return obj; } private static List findDataInfo(String tableName, StringBuilder whereBuilder, List<Object> param) { List<Object> list = new ArrayList<Object>(); if("Cat".equals(tableName)){ list.add(catList.get(0)); return list; } if("Dog".equals(tableName)){ list.add(dogList.get(0)); return list; } return list; } }
執(zhí)行完成之后,就可以獲取到咱們需要的數(shù)據(jù)了。
4.獲取到數(shù)據(jù)后,發(fā)送給另一端,進(jìn)行解析保存
/** * 保存待處理數(shù)據(jù) * * @param obj */ @Override public void saveOtherInfo(Object obj) throws Exception { // 首先得到pojo所定義的字段 Field[] fields = obj.getClass().getDeclaredFields(); for (Field curField : fields) { // 設(shè)置字段可訪問(必須,否則報(bào)錯(cuò)) curField.setAccessible(true); Class<?> curFieldType = curField.getType(); // 集合List元素 if (curFieldType.equals(List.class)) { // 當(dāng)前集合的泛型類型 Type genericType = curField.getGenericType(); if (null == genericType) { continue; } if (genericType instanceof ParameterizedType) { Object object = ReflectionUtil.getVlaue(obj,(String) curField.getName(),""); if(object!=null){ List list = (List)object; for (int i=0;i<list.size();i++){ Object o = list.get(i); // baseDao.saveOrUpdate(o); } } } }else{ System.out.println((curField.getName() + "--暫不支持的類型--" + curFieldType.getSimpleName())); } } }
這樣兩端進(jìn)行數(shù)據(jù)傳輸就完成了,或中間使用消息中間件進(jìn)行傳輸也是可以的。
以上就是利用Java實(shí)體bean對(duì)象批量數(shù)據(jù)傳輸處理的詳細(xì)內(nèi)容,更多關(guān)于java bean對(duì)象數(shù)據(jù)傳輸?shù)馁Y料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Java 如何使用@Autowired注解自動(dòng)注入bean
- java使用BeanUtils.copyProperties踩坑經(jīng)歷
- Java基礎(chǔ)之Bean的創(chuàng)建、定位和使用
- 常用json與javabean互轉(zhuǎn)的方法實(shí)現(xiàn)
- IDEA使用GsonFormat完成JSON和JavaBean之間的轉(zhuǎn)換
- Java 確保某個(gè)Bean類被最后執(zhí)行的幾種實(shí)現(xiàn)方式
- 如何動(dòng)態(tài)修改JavaBean中注解的參數(shù)值
- Java之SSM中bean相關(guān)知識(shí)匯總案例講解
相關(guān)文章
springcloud項(xiàng)目占用內(nèi)存好幾個(gè)G導(dǎo)致服務(wù)器崩潰的問題
這篇文章主要介紹了springcloud項(xiàng)目占用內(nèi)存好幾個(gè)G導(dǎo)致服務(wù)器崩潰的問題,本文給大家分享解決方案供大家參考,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10Java開發(fā)或調(diào)用WebService的幾種方式總結(jié)
java開發(fā)過程中,很多地方都會(huì)遇到數(shù)據(jù)傳遞,遠(yuǎn)程獲取數(shù)據(jù)問題,這篇文章主要介紹了Java開發(fā)或調(diào)用WebService的幾種方式的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-06-06SpringBoot響應(yīng)處理實(shí)現(xiàn)流程詳解
這篇文章主要介紹了SpringBoot響應(yīng)處理實(shí)現(xiàn)流程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-10-10淺析mybatis和spring整合的實(shí)現(xiàn)過程
據(jù)官方的說法,在Mybatis3問世之前,Spring3的開發(fā)工作就已經(jīng)完成了,所以Spring3中還是沒有對(duì)Mybatis3的支持。因此由Mybatis社區(qū)自己開發(fā)了一個(gè)Mybatis-Spring用來滿足Mybatis用戶整合Spring的需求,下面通過Mybatis-Spring來整合Mybatis跟Spring的用法做介紹2015-10-10Java Spring5學(xué)習(xí)之JdbcTemplate詳解
這篇文章主要介紹了Java Spring5學(xué)習(xí)之JdbcTemplate詳解,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-05-05