随笔-157  评论-1316  文章-3 

cassandra 数据到Java对象的映射绑定

类似Hibernate和MyBatis的关系映射,自动帮你将查询数据或是修改的参数进行数据映射和绑定。

支持查询后返回数据ResultSet到Java对象的映射,支持修改、删除、查询之前参数的绑定。

在JavaEntity的命名方式不合规范情况下,可以用Map进行绑定映射。

这种做法可以适用于JDBC的sql result到Java Entity的映射绑定,但需要修改少量的代码。

 

代码如下:

  1 package com.cnblogs.hoojo.cassar.utils;
  2 
  3 import java.beans.PropertyDescriptor;
  4 import java.lang.reflect.InvocationTargetException;
  5 import java.math.BigDecimal;
  6 import java.math.BigInteger;
  7 import java.net.InetAddress;
  8 import java.sql.Timestamp;
  9 import java.util.Date;
 10 import java.util.HashMap;
 11 import java.util.Iterator;
 12 import java.util.List;
 13 import java.util.Map;
 14 import java.util.Set;
 15 import java.util.UUID;
 16 
 17 import org.apache.commons.beanutils.PropertyUtils;
 18 import org.apache.commons.collections.MapUtils;
 19 import org.apache.commons.lang3.StringUtils;
 20 import org.slf4j.Logger;
 21 import org.slf4j.LoggerFactory;
 22 import org.springframework.beans.BeanUtils;
 23 
 24 import com.datastax.driver.core.BoundStatement;
 25 import com.datastax.driver.core.ColumnDefinitions;
 26 import com.datastax.driver.core.ColumnDefinitions.Definition;
 27 import com.datastax.driver.core.DataType;
 28 import com.datastax.driver.core.PreparedStatement;
 29 import com.datastax.driver.core.Row;
 30 import com.google.common.collect.Maps;
 31 
 32 /**
 33  * <b>function:</b> cassandra 到 JavaEntity 映射转换
 34  * @author hoojo
 35  * @createDate 2017-1-19 下午6:20:47
 36  * @file RowMapperUtils.java
 37  * @package com.cnblogs.hoojo.cassar.utils
 38  * @blog http://blog.csdn.net/IBM_hoojo
 39  * @email hoojo_@126.com
 40  * @version 1.0
 41  */
 42 public class RowMapperUtils {
 43 
 44     private static final Logger logger = LoggerFactory.getLogger(RowMapperUtils.class);
 45     
 46     public static boolean DEBUG = false;
 47     public static String LOG_LEVEL = "TRACE"; 
 48     
 49     /**
 50      * <b>function:</b> 将查询的Row转换到target 对象中返回
 51      * @author hoojo
 52      * @createDate 2017-1-20 下午5:36:20
 53      * @param target 返回Java对象
 54      * @param row {@link Row}
 55      * @return 返回Java对象
 56      */
 57     public static <T> T conversion(T target, Row row) {
 58         return conversion(target, row, null);
 59     }
 60     
 61     /**
 62      * <b>function:</b> 将查询的Row转换到target 对象中返回,row对象存在List、Set集合类型情况
 63      * @author hoojo
 64      * @createDate 2017-1-20 下午5:36:20
 65      * @param target 返回Java对象
 66      * @param row {@link Row}
 67      * @param genericClass List中存储值 的class类型
 68      * @return 返回Java对象
 69      */
 70     public static <T> T conversion(T target, Row row, Map<String, Class<?>> genericClass) {
 71         return conversion(target, row, genericClass, null);
 72     }
 73     
 74     /**
 75      * <b>function:</b> 将查询的Row转换到target 对象中返回,row对象存在List、Set、Map集合类型情况
 76      * @author hoojo
 77      * @createDate 2017-1-20 下午5:36:20
 78      * @param target 返回Java对象
 79      * @param row {@link Row}
 80      * @param valClass List中存储值 的class类型
 81      * @param keyClass List中存储Key 的class类型
 82      * @return 返回Java对象
 83      */
 84     @SuppressWarnings("unchecked")
 85     public static <T> T conversion(T target, Row row, Map<String, Class<?>> valClass, Map<String, Class<?>> keyClass) {
 86         Class<T> clazz = (Class<T>) target.getClass();
 87         return conversion(clazz, row, valClass, keyClass);
 88     }
 89     
 90     /**
 91      * <b>function:</b> 将查询的Row转换到clazz实例对象返回,row对象存在List、Set集合类型情况
 92      * @author hoojo
 93      * @createDate 2017-1-20 下午5:36:20
 94      * @param target 返回Java对象
 95      * @param row {@link Row}
 96      * @return 返回Java对象
 97      */
 98     public static <T> T conversion(Class<T> clazz, Row row) {
 99         return conversion(clazz, row, null);
100     }
101     
102     /**
103      * <b>function:</b> 将查询的Row转换到clazz实例对象返回,row对象存在List、Set集合类型情况
104      * @author hoojo
105      * @createDate 2017-1-20 下午5:36:20
106      * @param target 返回Java对象
107      * @param row {@link Row}
108      * @param genericClass List中存储值 的class类型
109      * @return 返回Java对象
110      */
111     public static <T> T conversion(Class<T> clazz, Row row, Map<String, Class<?>> genericClass) {
112         return conversion(clazz, row, genericClass, null);
113     }
114     
115     public static <T> T transform(T target, Row row, Map<String, Class<?>> valClass, Map<String, Class<?>> keyClass) {
116 
117         ColumnDefinitions cols = row.getColumnDefinitions();
118         Iterator<Definition> definitionIter = null;
119 
120         definitionIter = cols.iterator();
121         while (definitionIter.hasNext()) {
122             Definition definition = definitionIter.next();
123 
124             DataType type = definition.getType();
125             String columnName = definition.getName();
126             debug(String.format("列名:%s,列类型:%s", columnName, type));
127 
128             Object value = getData(row, type, columnName, valClass, keyClass);
129             debug(String.format("列名:%s,取值:%s", columnName, value));
130 
131             String camelName = camelName(columnName);
132             try {
133                 PropertyUtils.setProperty(target, camelName, value);
134             } catch (IllegalAccessException | InvocationTargetException e) {
135                 log("设置{}值发生异常:", camelName, e);
136             } catch (NoSuchMethodException ex) {
137                 
138                 if (camelName.equals(camelName.toLowerCase())) {
139                     log("This Class '{}' set '{}' method notfound.", new Object[] { target.getClass().getSimpleName(), camelName } );
140                 } else {
141                     
142                     try {
143                         PropertyUtils.setProperty(target, camelName.toLowerCase(), value);
144                     } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
145                         log("设置{}值发生异常:", camelName, e);
146                     } catch (NoSuchMethodException e) {
147                         log("This Class '{}' set '{}' or set '{}' method notfound.", new Object[] { target.getClass().getSimpleName(), camelName, camelName.toLowerCase() } );
148                     }
149                 }
150             }
151         }
152         debug("target: " + target);
153         
154         return target;
155     }
156     
157     /**
158      * <b>function:</b> 将查询的Row转换到clazz实例对象返回,row对象存在List、Set、Map集合类型情况
159      * @author hoojo
160      * @createDate 2017-1-20 下午5:36:20
161      * @param target 返回Java对象
162      * @param row {@link Row}
163      * @param valClass List中存储值 的class类型
164      * @param keyClass List中存储Key 的class类型
165      * @return 返回Java对象
166      */
167     public static <T> T conversion(Class<T> clazz, Row row, Map<String, Class<?>> valClass, Map<String, Class<?>> keyClass) {
168 
169         T target = BeanUtils.instantiate(clazz);
170         Map<String, PropertyDescriptor> mappedFields = getMappedFields(target.getClass());
171 
172         ColumnDefinitions cols = row.getColumnDefinitions();
173         Iterator<Definition> definitionIter = cols.iterator();
174         while (definitionIter.hasNext()) {
175             Definition definition = definitionIter.next();
176 
177             DataType type = definition.getType();
178             String columnName = definition.getName().toLowerCase();
179             debug(String.format("列名:%s,列类型:%s", columnName, type));
180 
181             Object value = getData(row, type, columnName, valClass, keyClass);
182             debug(String.format("列名:%s,取值:%s", columnName, value));
183 
184             if (mappedFields.containsKey(columnName)) {
185                 try {
186                     mappedFields.get(columnName).getWriteMethod().invoke(target, value); 
187                 } catch (IllegalAccessException | InvocationTargetException e) {
188                     log("设置{}值发生异常:{}", columnName, e);
189                 } catch (Exception e) {
190                     log("设置{}值发生异常:{}", columnName, e.getMessage());
191                 } 
192             } else {
193                 log("The target Class '{}' in Column '{}' setter method notFound", clazz.getSimpleName(), columnName);
194             }
195         }
196         debug("target: " + target);
197         
198         return target;
199     }
200     
201     /**
202      * <b>function:</b> 将查询的Row转换到target Map对象中返回
203      * @author hoojo
204      * @createDate 2017-1-20 下午5:36:20
205      * @param target 返回Map对象
206      * @param row {@link Row}
207      * @return 返回Map对象
208      */
209     public static <T> Map<String, T> conversion(Map<String, T> target, Row row) {
210         return conversion(target, row, null);
211     }
212     
213     /**
214      * <b>function:</b> 将查询的Row转换到target Map对象中返回,row对象存在List、Set集合类型情况
215      * @author hoojo
216      * @createDate 2017-1-20 下午5:36:20
217      * @param target 返回Map对象
218      * @param row {@link Row}
219      * @param genericClass List中存储值 的class类型
220      * @return 返回Map对象
221      */
222     public static <T> Map<String, T> conversion(Map<String, T> target, Row row, Map<String, Class<?>> genericClass) {
223         return conversion(target, row, genericClass, null);
224     }
225     
226     /**
227      * <b>function:</b> 将查询的Row转换到target Map对象中返回,row对象存在Map集合类型情况
228      * @author hoojo
229      * @createDate 2017-1-20 下午5:36:20
230      * @param target 返回Map对象
231      * @param row {@link Row}
232      * @param valClass MAP、List中存储值 的class类型
233      * @param keyClass MAP Key 的class类型
234      * @return 返回Map对象
235      */
236     @SuppressWarnings("unchecked")
237     public static <T> Map<String, T> conversion(Map<String, T> target, Row row, Map<String, Class<?>> valClass, Map<String, Class<?>> keyClass) {
238 
239         if (target == null) {
240             target = Maps.newHashMap();
241         }
242         
243         ColumnDefinitions cols = row.getColumnDefinitions();
244         Iterator<Definition> definitionIter = cols.iterator();
245         while (definitionIter.hasNext()) {
246             Definition definition = definitionIter.next();
247 
248             DataType type = definition.getType();
249             String columnName = definition.getName().toLowerCase();
250             debug(String.format("列名:%s,列类型:%s", columnName, type));
251 
252             Object value = getData(row, type, columnName, valClass, keyClass);
253             debug(String.format("列名:%s,取值:%s", columnName, value));
254 
255             String camelName = camelName(columnName);
256             if (value != null) {
257                 target.put(camelName, (T) value);
258             } else {
259                 target.put(camelName, null);
260             }
261         }
262         debug("target: " + target);
263         
264         return target;
265     }
266     
267     /**
268      * <b>function:</b> 为cql PreparedStatement对象自动绑定参数值
269      * @author hoojo
270      * @createDate 2017-1-20 下午5:33:18
271      * @param statement PreparedStatement
272      * @param params 参数实体
273      * @return BoundStatement 已绑定值
274      */
275     public static <T> BoundStatement bind(PreparedStatement statement, Map<String, T> bindParam) {
276         
277         BoundStatement boundStatement = null;
278         
279         Map<String, T> params = Maps.newHashMap(bindParam);
280         
281         Set<String> keys = bindParam.keySet();
282         Iterator<String> iter = keys.iterator();
283         while (iter.hasNext()) {
284             String key = iter.next();
285             T val = bindParam.get(key);
286             params.put(key, val);
287             
288             if (!bindParam.containsKey(key.toLowerCase())) {
289                 params.put(key.toLowerCase(), val);
290             }
291             
292             key = underscoreName(key).toLowerCase();
293             if (!bindParam.containsKey(key)) {
294                 params.put(key, val);
295             }
296         }
297         
298         Map<String, Object> bindParams = Maps.newLinkedHashMap();
299         
300         ColumnDefinitions cols = statement.getVariables();
301         Iterator<Definition> definitionIter = cols.iterator();
302         while (definitionIter.hasNext()) {
303             Definition definition = definitionIter.next();
304 
305             DataType type = definition.getType();
306             String columnName = definition.getName().toLowerCase();
307             debug(String.format("参数列名:%s,参数列类型:%s", columnName, type));
308             
309             Object param = null;
310             if (params.containsKey(columnName)) {
311                 param = params.get(columnName); 
312             } else {
313                 log("The target Map does not exist param '{}' value.", columnName);
314             }
315             debug(String.format("参数列名:%s,参数取值:%s", columnName, param));
316             
317             bindParams.put(columnName, param);
318         }
319          
320         debugCQL(statement.getQueryString(), bindParams);
321         
322         boundStatement = statement.bind(bindParams.values().toArray());
323         return boundStatement;
324     }
325     
326     /**
327      * <b>function:</b> 为cql PreparedStatement对象自动绑定参数值
328      * @author hoojo
329      * @createDate 2017-1-20 下午5:33:18
330      * @param statement PreparedStatement
331      * @param bindEntity 参数实体
332      * @return BoundStatement 已绑定值
333      */
334     public static <T> BoundStatement bind(PreparedStatement statement, T bindEntity) {
335         
336         BoundStatement boundStatement = null;
337             
338         Map<String, Object> params = Maps.newLinkedHashMap();
339         Map<String, PropertyDescriptor> mappedFields = getMappedFields(bindEntity.getClass());
340         
341         ColumnDefinitions cols = statement.getVariables();
342         Iterator<Definition> definitionIter = cols.iterator();
343         while (definitionIter.hasNext()) {
344             Definition definition = definitionIter.next();
345 
346             DataType type = definition.getType();
347             String columnName = definition.getName().toLowerCase();
348             debug(String.format("参数列名:%s,参数列类型:%s", columnName, type));
349             
350             Object param = null;
351             if (mappedFields.containsKey(columnName)) {
352                 try {
353                     param = mappedFields.get(columnName).getReadMethod().invoke(bindEntity); 
354                 } catch (IllegalAccessException | InvocationTargetException e) {
355                     log("设置{}值发生异常:", columnName, e);
356                 } 
357             } else {
358                 log("The target Class '{}' in Column '{}' getter method notFound", bindEntity.getClass().getSimpleName(), columnName);
359             }
360             debug(String.format("参数列名:%s,参数取值:%s", columnName, param));
361             
362             params.put(columnName, param);
363         }
364          
365         debugCQL(statement.getQueryString(), params);
366         
367         boundStatement = statement.bind(params.values().toArray());
368         return boundStatement;
369     }
370     
371     /**
372      * <b>function:</b> 调试cql语句,将占位符替换参数值
373      * @author hoojo
374      * @createDate 2017-1-20 下午5:30:48
375      * @param queryString cql语句
376      * @param params 参数
377      */
378     private static void debugCQL(String queryString, Map<String, Object> params) {
379         
380         if (DEBUG) {
381             Set<String> keys = params.keySet();
382             
383             Object[] keyArrays = keys.toArray();
384             for (int i = 0; i < keys.size(); i++) {
385                 
386                 queryString = StringUtils.replaceOnce(queryString, "?", MapUtils.getString(params, keyArrays[i], "NULL"));
387             }
388             logger.info("debug cql: {}", queryString);
389         }
390     }
391     
392     private static void debug(String log) {
393         
394         if (DEBUG) {
395             logger.info(log);
396         }
397     }
398     
399     private static void log(String msg, Object... args) {
400         
401         if ("INFO".equalsIgnoreCase(LOG_LEVEL)) {
402             logger.info(msg, args);
403         } else if ("WARN".equalsIgnoreCase(LOG_LEVEL)) {
404             logger.warn(msg, args);
405         } else if ("DEBUG".equalsIgnoreCase(LOG_LEVEL)) {
406             logger.debug(msg, args);
407         } else if ("TRACE".equalsIgnoreCase(LOG_LEVEL)) {
408             logger.trace(msg, args);
409         } else if ("ERROR".equalsIgnoreCase(LOG_LEVEL)) {
410             logger.error(msg, args);
411         }
412     }
413     
414     /**
415      * <b>function:</b> 获取对象的setter方法,并返回下划线命名和全小写命名的Map集合
416      * @author hoojo
417      * @createDate 2017-1-20 下午5:31:21
418      * @param clazz 目标对象class
419      * @return Map
420      */
421     private static Map<String, PropertyDescriptor> getMappedFields(Class<?> clazz) {
422         Map<String, PropertyDescriptor> mappedFields = new HashMap<String, PropertyDescriptor>();
423         
424         PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(clazz);
425         for (PropertyDescriptor pd : pds) {
426             if (pd.getWriteMethod() != null) {
427                 
428                 //setUserId->userid,user_id;
429                 mappedFields.put(pd.getName().toLowerCase(), pd);
430                 
431                 String underscoreName = underscoreName(pd.getName());
432                 if (!pd.getName().toUpperCase().equals(underscoreName)) {
433                     mappedFields.put(underscoreName.toLowerCase(), pd);
434                 }
435             }
436         }
437         
438         return mappedFields;
439     }
440     
441     /**
442      * <b>function:</b> 获取cql 的值
443      * @author hoojo
444      * @createDate 2017-1-20 下午5:26:24
445      * @param row {@link Row}
446      * @param type 列类型
447      * @param columnName 列名
448      * @param valClass MAP、List中存储值 的class类型
449      * @param keyClass MAP Key 的class类型
450      * @return
451      */
452     private static Object getData(Row row, DataType type, String columnName, Map<String, Class<?>> valClass, Map<String, Class<?>> keyClass) {
453         
454         Object value = null;
455         
456         try {
457 
458             if (type == DataType.bigint()) {
459                 value = row.getLong(columnName);
460             } else if (type == DataType.cboolean()) {
461                 value = row.getBool(columnName);
462             } else if (type == DataType.blob()) {
463                 value = row.getBytes(columnName);
464             } else if (type == DataType.timestamp()) {
465                 value = row.getDate(columnName);
466             } else if (type == DataType.decimal()) {
467                 value = row.getDecimal(columnName);
468             } else if (type == DataType.cfloat()) {
469                 value = row.getFloat(columnName);
470             } else if (type == DataType.inet()) {
471                 value = row.getInet(columnName);
472             } else if (type == DataType.cint()) {
473                 value = row.getInt(columnName);
474             } else if (type.isCollection() && type.asJavaClass() == List.class) {
475                 value = getCollectionData(row, type, columnName, valClass);
476             } else if (type.isCollection() && type.asJavaClass() == Set.class) {
477                 value = getCollectionData(row, type, columnName, valClass);
478             } else if (type.isCollection() && type.asJavaClass() == Map.class) {
479                 value = getCollectionData(row, type, columnName, valClass, keyClass);
480             } else if (type == DataType.varchar()) {
481                 value = row.getString(columnName);
482             } else if (type == DataType.uuid() || type == DataType.timeuuid()) {
483                 value = row.getUUID(columnName);
484             } else if (type == DataType.varint()) {
485                 value = row.getVarint(columnName);
486             } else if (type == DataType.cdouble()) {
487                 value = row.getDouble(columnName);
488             } else if (type == DataType.text()) {
489                 value = row.getString(columnName);
490             }
491             
492         } catch (Exception e) {
493             log("获取{}值发生异常:", columnName, e);
494         }
495         
496         if (value == null) {
497             log("Column '{}' Type({}) get cassandra data is NULL.", columnName, type);
498         }
499         
500         return value;
501     }
502     
503     /**
504      * <b>function:</b> 获取cql List集合泛型的值
505      * @author hoojo
506      * @createDate 2017-1-20 下午5:26:24
507      * @param row {@link Row}
508      * @param type 列类型
509      * @param columnName 列名
510      * @param valClass List Value 的class类型
511      * @return
512      */
513     private static Object getCollectionData(Row row, DataType type, String columnName, Map<String, Class<?>> valClass) {
514         
515         Object value = null;
516         
517         Class<?> ofValueType = valClass != null ? valClass.get(columnName) : null;
518         List<DataType> typeArguments = type.getTypeArguments();
519         if (ofValueType == null) {
520             log("Column TypeArguments convter Error, CQL Type: '{} {}' --> '{} {}(NULL)'", new Object[] { columnName, type, columnName, type.getName() });
521         } else if (ofValueType != typeArguments.get(0).asJavaClass()) {
522             log("Column TypeArguments convter Error, CQL Type: '{} {}({})' --> '{} {}({})'", new Object[] { columnName, type, typeArguments.get(0).asJavaClass(), columnName, valueOf(type.asJavaClass(), ofValueType), ofValueType });
523         } else if (type.asJavaClass() == List.class) {
524             value = row.getList(columnName, ofValueType);
525         } else if (type.asJavaClass() == Set.class) {
526             value = row.getSet(columnName, ofValueType);
527         }
528         
529         return value;
530     }
531     
532     /**
533      * <b>function:</b> 获取cql MAP集合泛型的值
534      * @author hoojo
535      * @createDate 2017-1-20 下午5:26:24
536      * @param row {@link Row}
537      * @param type 列类型
538      * @param columnName 列名
539      * @param valClass MAP Value 的class类型
540      * @param keyClass MAP Key 的class类型
541      * @return
542      */
543     private static Object getCollectionData(Row row, DataType type, String columnName, Map<String, Class<?>> valClass, Map<String, Class<?>> keyClass) {
544         
545         Object value = null;
546         
547         Class<?> ofKeyType = keyClass != null ? keyClass.get(columnName) : null;
548         Class<?> ofValueType = valClass != null ? valClass.get(columnName) : null;
549         
550         List<DataType> typeArguments = type.getTypeArguments();
551         if (ofValueType == null && ofKeyType == null) {
552             log("Column TypeArguments convter Error, CQL Type: '{} {}' --> '{} {}<NULL, NULL>'", new Object[] { columnName, type, columnName, type.getName() });
553         } else if (ofValueType == null) {
554             log("Column TypeArguments convter Error, CQL Type: '{} {}' --> '{} {}<{}, NULL>'", new Object[] { columnName, type, columnName, type.getName(), valueOf(ofKeyType) });
555         } else if (ofKeyType == null) {
556             log("Column TypeArguments convter Error, CQL Type: '{} {}' --> '{} {}<NULL, {}>'", new Object[] { columnName, type, columnName, type.getName(), valueOf(ofValueType) });
557         } else if (ofKeyType != typeArguments.get(0).asJavaClass() || ofValueType != typeArguments.get(1).asJavaClass()) {
558             log("Column TypeArguments convter Error, CQL Type: '{} {} (<{}, {}>)' --> '{} {}(<{}, {}>)'", new Object[] { columnName, type, typeArguments.get(0).asJavaClass(), typeArguments.get(1).asJavaClass(), columnName, valueOf(Map.class, ofValueType, ofKeyType), ofKeyType, ofValueType });
559         } else {
560             value = row.getMap(columnName, ofKeyType, ofValueType);
561         }
562         
563         return value;
564     }
565     
566     /**
567      * <b>function:</b> 转换为下划线命名方式
568      * @author hoojo
569      * @createDate 2017-1-20 下午5:24:50
570      */
571     public static String underscoreName(String name) {
572         StringBuilder result = new StringBuilder();
573         if (name != null && name.length() > 0) {
574             // 将第一个字符处理成大写
575             result.append(name.substring(0, 1).toUpperCase());
576             // 循环处理其余字符
577             for (int i = 1; i < name.length(); i++) {
578                 String s = name.substring(i, i + 1);
579                 // 在大写字母前添加下划线
580                 if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
581                     result.append("_");
582                 }
583                 // 其他字符直接转成大写
584                 result.append(s.toUpperCase());
585             }
586         }
587         return result.toString();
588     }
589     
590     /**
591      * <b>function:</b> 驼峰式命名方式
592      * @author hoojo
593      * @createDate 2017-1-20 下午5:25:09
594      */
595     public static String camelName(String name) {
596         StringBuilder sb = new StringBuilder();
597         if (!name.contains("_")) {
598             // 不含下划线,仅将首字母小写
599             return name.substring(0, 1).toLowerCase() + name.substring(1);
600         }
601         // 用下划线将原始字符串分割
602         String camels[] = name.split("_");
603         for (String camel :  camels) {
604             // 跳过原始字符串中开头、结尾的下换线或双重下划线
605             if (camel.isEmpty()) {
606                 continue;
607             }
608             // 处理真正的驼峰片段
609             if (sb.length() == 0) {
610                 // 第一个驼峰片段,全部字母都小写
611                 sb.append(camel.toLowerCase());
612             } else {
613                 // 其他的驼峰片段,首字母大写
614                 sb.append(camel.substring(0, 1).toUpperCase());
615                 sb.append(camel.substring(1).toLowerCase());
616             }
617         }
618         return sb.toString();
619     }
620 
621     /**
622      * <b>function:</b> java class转换到cql类型
623      * @author hoojo
624      * @createDate 2017-1-20 下午5:24:09
625      * @param clazz Class
626      * @return {@link DataType}
627      */
628     private static DataType valueOf(Class<?> clazz) {
629         
630         if (clazz == null) {
631             return DataType.custom("NULL");
632         }
633         if (clazz == long.class || clazz == Long.class) {
634             return DataType.bigint();
635         }
636         if (clazz == boolean.class || clazz == Boolean.class) {
637             return DataType.cboolean();
638         }
639         if (clazz == Byte.class || clazz == byte.class) {
640             return DataType.blob();
641         }
642         if (clazz == Date.class || clazz == Timestamp.class) {
643             return DataType.timestamp();
644         }
645         if (clazz == BigDecimal.class) {
646             return DataType.decimal();
647         }
648         if (clazz == float.class || clazz == Float.class) {
649             return DataType.cfloat();
650         }
651         if (clazz == InetAddress.class) {
652             return DataType.inet();
653         }
654         if (clazz == int.class || clazz == Integer.class) {
655             return DataType.cint();
656         }
657         if (clazz == String.class) {
658             return DataType.varchar();// text();
659         }
660         if (clazz == UUID.class) {
661             return DataType.uuid(); // timeuuid();
662         }
663         if (clazz == BigInteger.class) {
664             return DataType.varint();
665         }
666         
667         log("Class '{}' unknow DataType in cassandra.", clazz);
668         
669         return DataType.custom("unknow");
670     }
671     
672     /**
673      * <b>function:</b> 转换集合list、set到cql类型
674      * @author hoojo
675      * @createDate 2017-1-20 下午5:22:43
676      * @param clazz java class
677      * @param valueClass 集合值存储类型class
678      * @param keyClass 集合键存储类型class
679      * @return DataType
680      */
681     public static DataType valueOf(Class<?> clazz, Class<?> valueClass, Class<?> keyClass) {
682         
683         if (clazz == List.class) {
684             return DataType.list(valueOf(valueClass));
685         }
686         if (clazz == Set.class) {
687             return DataType.set(valueOf(valueClass));
688         }
689         if (clazz == Map.class) {
690             return DataType.map(valueOf(keyClass), valueOf(valueClass));
691         }
692         
693         log("Class '{}' unknow DataType in cassandra.", clazz);
694         return DataType.custom("unknow");
695     }
696     
697     /**
698      * <b>function:</b> 转换集合list、set到cql类型
699      * @author hoojo
700      * @createDate 2017-1-20 下午5:22:43
701      * @param clazz java class
702      * @param valueClass 集合存储类型class
703      * @return DataType
704      */
705     private static DataType valueOf(Class<?> clazz, Class<?> valueClass) {
706         
707         return valueOf(clazz, valueClass, null);
708     }
709 }

 

posted on 2017-03-03 10:22 hoojo 阅读(...) 评论(...) 编辑 收藏