vue项目接口域名动态的获取方法
758
2023-04-28
Java中Boolean与字符串或者数字1和0的转换实例
mysql有个字段是bit,只存储1和0,是二进制存储,那么在java的dao层如何映射成boolean呢
@Column(name="is_standard")
private boolean isStandard;
public void setIsStandard(boolean isStandard){
this.isStandard = isStandard;
}
public boNaSFYzNolean getIsStandard(){
return isStandard;
}
其实就是在底层dao做反射的时候,先判断字段(比如isStandard)的字段类型是否为boolean,如果是,则在查出数据库字段bit is_standard的时候,做转换
private List
List
List
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnsCount = rsmd.getColumnCount();
List
for(int i = 0; i < columnsCount; i++){
columnNameList.add(rsmd.getColumnLabel(i+1).toLowerCase());
}
while (resultSet.next()) {
T bean = clazz.newInstance();
for(Field f : fieldList) {
String columnName = MappingAnnotationUtil.getDBCloumnName(clazz, f).toLowerCase();
if(columnNameList.contains(columnName)) {
Object columnValueObj = null;
Class> filedCls = f.getType()http://;
if(filedCls == int.class || filedCls == Integer.class) {
columnValueObj = resultSet.getInt(columnName);
} else if(filedCls == String.class) {
columnValueObj = resultSet.getString(columnName);
} else if(filedCls == boolean.class || filedCls == Boolean.class) {
columnValueObj = resultSet.getBoolean(columnName);
} else if(filedCls == byte.class || filedCls == Byte.class) {
columnValueObj = resultSet.getByte(columnName);
} else if(filedCls == short.class || filedCls == Short.class) {
columnValueObj = resultSet.getShort(columnName);
} else if(filedCls == long.class || filedCls == Long.class) {
columnValueObj = resultSet.getLong(columnName);
} else if(filedCls == float.class || filedCls == Float.class) {
columnValueObj = resultSet.getFloat(columnName);
} else if(filedCls == double.class || filedCls == Double.class) {
columnValueObj = resultSet.getDouble(columnName);
} else if(filedCls == BigDecimal.class) {
columnValueObj = resultSet.getBigDecimal(columnName);
}
else {
columnValueObj = resultSet.getObject(columnName);
}
if (columnValueObj != null) {
Method setterMethod = MappingAnnotationUtil.getSetterMethod(clazz, f);
setterMethod.invoke(bean, new Object[] { columnValueObj });
}
}
}
dataList.add(bean);
}
return dataList;
}
注意这个
else if(filedCls == boolean.class || filedCls == Boolean.class) {
columnValueObj = resultSet.getBoolean(columnName);
}
resultSet.getBoolean(columnName) 就是转换的方法,具体实现为
for (int i = 0; i < trueStrings.length; ++i) {
if (trueStrings[i].equals(stringValue)) {
return type.cast(Boolean.TRUE);
}
}
for (int i = 0; i < falseStrings.length; ++i) {
if (falseStrings[i].equals(stringValue)) {
return type.cast(Boolean.FALSE);
}
}
核心原理就是根据字符串/数字做对比,如果是1,0就返回true/false,其它的直接返回false或抛出异常,字符串如果是[true, yes, y, on, 1]就返回true,如果是[false, no, n, off, 0]就返回false
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~