Java反射 JavaBean對象自動生成插入,更新,刪除,查詢sql語句操作
通過反射根據(jù)提供的表名、POJO類型、數(shù)據(jù)對象自動生成sql語句。
如名為 User 的JavaBean與名為 user 的數(shù)據(jù)庫表對應(yīng),可以提供一個封裝有數(shù)據(jù)的User對象user,根據(jù)user中含有的數(shù)據(jù)自動生成sql語句。
1、生成插入語句(插入user中包含的非空數(shù)據(jù)的語句):
String insertSql = getInsertSql("user", User.class, user);
2、生成更新語句(user中id不能為空):
String updateSql = getUpdateSql("user", User.class, user);
3、生成刪除語句(根據(jù)user中第一個非空屬性值作為查找條件刪除):
//生成刪除id為1的語句 User user = new User(); user.setId(1); String deleteSql = getDeleteSql("user", User.class, user);
4、生成查詢語句(根據(jù)user中第一個非空屬性值為查找條件):
//生成查詢id為1的語句 User user = new User(); user.setId(1); String selectSql = getSelectSql("user", User.class, user);
package com.hims.util; import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.StrUtil; import com.hims.bean.User; import java.lang.reflect.Field; public class ProduceSql { //String insertSql = getInsertSql("user", User.class, user); /** * 生成插入語句 * @param tablename 表明 * @param t 有數(shù)據(jù)的實(shí)體 * @param <T> 數(shù)據(jù)實(shí)體類型 如 User */ public static <T> String getInsertSql(String tablename, T t) throws IllegalArgumentException { //insert into table_name (column_name1,column_name2, ...) values (value1,value2, ...) boolean flag = false; String sql = ""; Field[] fields = ReflectUtil.getFieldsDirectly(t.getClass(), false); StringBuffer topHalf = new StringBuffer("insert into "+tablename+" ("); StringBuffer afterAalf = new StringBuffer("values ("); for (Field field : fields) { if ("ID".equals(field.getName()) || "id".equals(field.getName())){ continue; //id 自動生成無需手動插入 } topHalf.append(field.getName() + ","); if (ReflectUtil.getFieldValue(t, field.getName()) instanceof String) { afterAalf.append("'" + ReflectUtil.getFieldValue(t, field.getName()) + "',"); flag = true; } else { afterAalf.append(ReflectUtil.getFieldValue(t, field.getName()) + ","); flag = true; } } if (!flag) { throw new IllegalArgumentException(t.getClass() + "NullException.\nThere is no attribute that is not empty.You must provide an object with at least one attribute."); } topHalf = new StringBuffer(StrUtil.removeSuffix(topHalf.toString(), ",")); afterAalf = new StringBuffer(StrUtil.removeSuffix(afterAalf.toString(), ",")); topHalf.append(") "); afterAalf.append(") "); sql = topHalf.toString() + afterAalf.toString(); return sql; } /** * 生成更新語句 * 必須含有id * 數(shù)據(jù)實(shí)體中 null 與 空字段不參與更新 * @param tablename 數(shù)據(jù)庫中的表明 * @param t 有數(shù)據(jù)的實(shí)體 * @param <T> 數(shù)據(jù)實(shí)體類型,如 User */ public static <T> String getUpdateSql(String tablename, T t) throws IllegalArgumentException { //UPDATE table_name SET column_name1 = value1, column_name2 = value2, ... where ID=xxx //or //UPDATE table_name SET column_name1 = value1, column_name2 = value2, ... where id=xxx boolean flag = false; String sql = ""; String id = ""; //保存id列名:ID or id Field[] fields = ReflectUtil.getFieldsDirectly(t.getClass(), false); sql = "update "+tablename+" set "; for (Field field : fields) { StringBuffer tmp = new StringBuffer(); if ("ID".equals(field.getName()) || "id".equals(field.getName())){ id = field.getName(); continue;//更新的時候無需set id=xxx } if (ReflectUtil.getFieldValue(t, field.getName()) != null && (String)ReflectUtil.getFieldValue(t, field.getName()) != "") { tmp.append( field.getName() + "="); if (ReflectUtil.getFieldValue(t, field.getName()) instanceof String) { tmp.append( "'" + ReflectUtil.getFieldValue(t, field.getName()) + "',"); flag = true; } else { tmp.append(ReflectUtil.getFieldValue(t, field.getName()) + ","); flag = true; } sql += tmp; } } if (!flag) { throw new IllegalArgumentException(t.getClass() + "NullException.\nThere is no attribute that is not empty except for ID.You must provide an object with at least one attribute exclude ID."); } sql = StrUtil.removeSuffix(sql, ",") + " where " + id + "='" + ReflectUtil.getFieldValue(t, id)+"'"; return sql; } /** * 生成刪除語句 * 根據(jù) user 中第一個不為空的字段刪除,應(yīng)該盡量使用 id,提供至少一個非空屬性 * @param tablename 表明 * @param t 有數(shù)據(jù)的實(shí)體 * @param <T> 數(shù)據(jù)實(shí)體類型 如 User */ public static <T> String getDeleteSql(String tablename, T t) throws IllegalArgumentException { //delete from table_name where column_name = value return getSelectOrDeleteSql(tablename, t, "delete"); } /** * 生成查詢語句 * 根據(jù) user 中第一個不為空的字段查詢 * @param tablename 表名 * @param t 有數(shù)據(jù)的實(shí)體 * @param <T> 數(shù)據(jù)實(shí)體類型 如 User */ public static <T> String getSelectSql(String tablename, T t) throws IllegalArgumentException { //delete from table_name where column_name = value return getSelectOrDeleteSql(tablename, t, "select *"); } /** * 根據(jù) operation 生成一個如:operation from table_name where column_name = value 的sql語句 * @param tablename * @param t * @param operation "select *" or "delete" * @param <T> * @return * @throws IllegalArgumentException */ private static <T> String getSelectOrDeleteSql(String tablename, T t, String operation) throws IllegalArgumentException { //operation from table_name where column_name = value boolean flag = false; String sql = ""; Field[] fields = ReflectUtil.getFieldsDirectly(t.getClass(), false); StringBuffer topHalf = new StringBuffer(operation + " from " + tablename + " where "); for (Field field : fields) { if ("ID".equals(field.getName()) || "id".equals(field.getName())) { if (ReflectUtil.getFieldValue(t, field.getName()) != null && (int)ReflectUtil.getFieldValue(t, field.getName()) != 0) { //id 不為空 topHalf.append(field.getName() + " = " + ReflectUtil.getFieldValue(t, field.getName())); flag = true; break; } } else { if (ReflectUtil.getFieldValue(t, field.getName()) != null && (String)ReflectUtil.getFieldValue(t, field.getName()) != "") { topHalf.append(field.getName() + " = '" + ReflectUtil.getFieldValue(t, field.getName()) + "'"); flag = true; break; } } } if (!flag) { throw new IllegalArgumentException(t.getClass() + "NullException.\nThere is no attribute that is not empty.You must provide an object with at least one attribute."); } sql = topHalf.toString(); return sql; } }
補(bǔ)充知識:通過java反射實(shí)現(xiàn)對javabean生成各種sql語句
通過java反射實(shí)現(xiàn)對javabean生成各種sql語句,有請大家評論,更改
package com.pdt.util; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; public class BeanUtil { /** * @param args */ public static void main(String[] args) { System.out.println(getBeanFilesList("com.pdt.bean.Dictionary")); System.out.println(genCreateTableSql("com.pdt.bean.Dictionary")); System.out.println(genInsertSql("com.pdt.bean.Dictionary")); } public static String getBeanName(String bean){ try { Class clz = Class.forName(bean); String clzStr = clz.toString(); //得到類名 String beanName = clzStr.substring(clzStr.lastIndexOf(".")+1).toLowerCase(); return beanName; } catch (ClassNotFoundException e) { e.printStackTrace(); return ""; } } public static List<String> getBeanPropertyList(String bean){ try { Class clz = Class.forName(bean); Field[] strs = clz.getDeclaredFields(); List<String> propertyList = new ArrayList<String>(); for (int i = 0; i < strs.length; i++) { String protype = strs[i].getType().toString(); propertyList.add(protype.substring(protype.lastIndexOf(".")+1)+"`"+strs[i].getName()); } return propertyList; } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } } public static String getBeanFilesList(String bean){ try { Class clz = Class.forName(bean); Field[] strs = clz.getDeclaredFields(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < strs.length; i++) { String protype = strs[i].getType().toString(); if (!strs[i].getName().equals("tableName")&&!strs[i].getType().equals("List")) { sb.append(strs[i].getName()+","); } } sb.deleteCharAt(sb.toString().lastIndexOf(",")); return sb.toString(); } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } } /** * 生成建表語句 * @param bean * @return */ public static String genCreateTableSql(String bean){ List<String> beanPropertyList = getBeanPropertyList(bean); StringBuffer sb = new StringBuffer("create table wnk_pdt_"+getBeanName(bean)+"(\n"); for (String string : beanPropertyList) { String[] propertys = string.split("`"); if (!propertys[1].equals("tableName")&&!propertys[1].equals("param")&&!propertys[0].equals("List")) { if (propertys[1].equals("id")) { sb.append(" id bigint primary key auto_increment,\n"); } else { if (propertys[0].equals("int")) { sb.append(" " + propertys[1] + " int default 0 comment '',\n"); } else if (propertys[0].equals("String")) { sb.append(" " + propertys[1] + " varchar(2000) default '' comment '',\n"); } else if (propertys[0].equals("double")) { sb.append(" " + propertys[1] + " double(10,2) default 0.0 comment '',\n"); } else if (propertys[0].equals("Date")) { sb.append(" " + propertys[1] + " datetime comment '',\n"); } } } } sb.append(")"); sb.deleteCharAt(sb.lastIndexOf(",")); return sb.toString(); } /** * 生成查詢語句 * @param bean * @return */ public static String genSelectAllSql(String bean){ String filesList = getBeanFilesList(bean); return "select \n "+filesList+" \n from \n wnk_pdt_"+getBeanName(bean)+""; } /** * 生成插入語句 * @param bean * @return */ public static String genInsertSql(String bean){ String filesList = getBeanFilesList(bean); int fl = DataUtil.getCountSonStr(filesList,",")+1; String wenhao = ""; for (int i = 0; i < fl; i++) { if(i==fl-1){ wenhao = wenhao+"?"; }else{ wenhao = wenhao+"?,"; } } return "insert into wnk_pdt_"+getBeanName(bean)+"("+filesList+") values("+wenhao+")"; } }
以上這篇Java反射 JavaBean對象自動生成插入,更新,刪除,查詢sql語句操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)CSV格式轉(zhuǎn)對象
csv全稱“Comma-Separated Values”,是一種逗號分隔值格式的文件,常用來存儲數(shù)據(jù)的純文本格式文件。本文將用Java語言實(shí)現(xiàn)CSV轉(zhuǎn)對象,需要的可以參考一下2022-06-06使用Java代碼實(shí)現(xiàn)RocketMQ的生產(chǎn)與消費(fèi)消息
這篇文章介紹一下其他的小組件以及使用Java代碼實(shí)現(xiàn)生產(chǎn)者對消息的生成,消費(fèi)者消費(fèi)消息等知識點(diǎn),并通過代碼示例介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-07-07詳解Java如何實(shí)現(xiàn)加密或者解密PDF文檔
PDF文檔加密是一種用于保護(hù)文件內(nèi)容的功能。這篇文章主要介紹了Java實(shí)現(xiàn)加密或者解密PDF文檔的方法,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-03-03Spring中的@Conditional注解實(shí)現(xiàn)分析
這篇文章主要介紹了Spring中的@Conditional注解實(shí)現(xiàn)分析, @Conditional是Spring 4出現(xiàn)的注解,但是真正露出價(jià)值的是Spring Boot的擴(kuò)展@ConditionalOnBean等,需要的朋友可以參考下2023-12-12Spring Boot中配置定時任務(wù)、線程池與多線程池執(zhí)行的方法
這篇文章主要給大家介紹了關(guān)于Spring Boot中配置定時任務(wù)、線程池與多線程池執(zhí)行的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09spring NamedContextFactory實(shí)現(xiàn)服務(wù)隔離的示例詳解
假設(shè)我們有個場景,我們需要實(shí)現(xiàn)服務(wù)之間的數(shù)據(jù)隔離、配置隔離、依賴的spring bean之間隔離,大家會有什么實(shí)現(xiàn)思路?今天給大家介紹spring-cloud-context里面有個NamedContextFactory可以達(dá)到上面的效果,需要的朋友可以參考下2024-05-05