dao layer and xml parameter binding in mybatis 3.5.0/mybatis plus 3.x is complete (unlike older versions)

Posted by redbrad0 on Sat, 31 Aug 2019 06:26:49 +0200

Mode 1 (not recommended) Single parameter mode

@Mapper
public interface UserDao extends BaseMapper<User> {
   User selectList1(String username, String phone);
}
<select id="selectList1" resultMap="BaseResultMap">
   select * from user where username= #{arg0} and phone=#{arg1}
</select>

Note: select * from user where username= #{0} and phone=#{1} are incorrect in the new version and will report errors:

nested exception is org.apache.ibatis.binding.BindingException: Parameter '0' not found. Available parameters are [arg1, arg0, param1, param2]

Looking at error and error information shows that you can also do this

<select id="selectList1" resultMap="BaseResultMap">
   select * from user where username= #{param1} and phone=#{param2}
</select>

 

Mode 2 (recommended) Entity class object mode

This method is compatible with previous versions and has not changed

@Mapper
public interface UserDao extends BaseMapper<User> {
    User selectList1(@Param("username") String username,@Param("phone") String phone);
}
<select id="selectList1" resultMap="BaseResultMap">
   select * from user where username= #{username} and phone=#{phone}
</select>

perhaps

 <select id="selectList1" resultMap="BaseResultMap" parameterType="com.bdkt.course.model.User">
    select * from user where username= #{username} and phone=#{phone}
 </select>

Either way

 

Mode 3 uses the bean tool class to convert to map, map type parameter (recommended)

bean Tool Class

import com.alibaba.fastjson.JSONObject;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
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;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class QueryEntityTools {

	public static Map<String, Object> objectToMap(Object obj) {
		if (obj == null) {
			return null;
		}

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Field[] declaredFields = obj.getClass().getDeclaredFields();
			for (Field field : declaredFields) {
				field.setAccessible(true);
				map.put(field.getName(), field.get(obj));
			}
		} catch (Exception e) {

		}

		return map;
	}

	/**
	 * Convert Entities to Map s
	 * 
	 * @param bean
	 * @return
	 */
	public static Map<String, Object> beanToMap(Object bean) {
		Class<?> type = bean.getClass();
		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(type);
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (int i = 0; i < propertyDescriptors.length; i++) {
				PropertyDescriptor descriptor = propertyDescriptors[i];
				String propertyName = descriptor.getName();
				if (!propertyName.equals("class")) {
					Method readMethod = descriptor.getReadMethod();
					if (readMethod != null) {
						Object result = readMethod.invoke(bean, new Object[0]);
						if (result != null) {
							returnMap.put(propertyName, result);
						} else {
							returnMap.put(propertyName, "");
						}
					}
				}
			}
		} catch (Exception e) {
			returnMap.put("error", e.getMessage());
		}
		return returnMap;
	}

	/**
	 * Convert Entity to Json
	 * 
	 * @param bean
	 * @return
	 */
	public static JSONObject beanToJson(Object bean) {
		Class<?> type = bean.getClass();
		JSONObject json = new JSONObject();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(type);
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (int i = 0; i < propertyDescriptors.length; i++) {
				PropertyDescriptor descriptor = propertyDescriptors[i];
				String propertyName = descriptor.getName();
				if (!propertyName.equals("class")) {
					Method readMethod = descriptor.getReadMethod();
					if (readMethod != null) {
						Object result = readMethod.invoke(bean, new Object[0]);
						if (result != null) {
							json.put(propertyName, result);
						} else {
							json.put(propertyName, "");
						}
					}
				}
			}
		} catch (Exception e) {
			json.put("error", e.getMessage());
		}
		return json;
	}

	/**
	 * Convert map to Json
	 */
	public static JSONObject mapToJson(Map<String, ? extends Object> map) {
		JSONObject json = new JSONObject();
		for (String key : map.keySet()) {
			json.put(key, map.get(key));
		}
		return json;
	}

	/**
	 * Convert map to entity
	 * 
	 * @param map
	 * @param bean
	 * @return
	 */
	public static <T, K, v> T mapToBean(Map<K, v> map, Class<T> bean) {
		T t = null;
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(bean);
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			t = bean.newInstance();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				if (map.containsKey(key)) {
					Object value = map.get(key);
					Method setter = property.getWriteMethod();
					if (checkType(value, property.getPropertyType())) {
						setter.invoke(t, value);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}

	private static boolean checkType(Object a, Class<?> b) {
		Class<? extends Object> oc = a.getClass();
		if (oc == b || oc.getSuperclass() == b || checkInterfaces(oc.getInterfaces(), b)) {
			return true;
		} else {
			return false;
		}
	}

	private static boolean checkInterfaces(Class<?>[] cArray, Class<?> b) {
		boolean tag = false;
		for (Class<?> c : cArray) {
			if (c == b) {
				tag = true;
				break;
			}
		}
		return tag;
	}

	/**
	 * Map List To Bean List
	 * @param bean
	 * @return
	 */
	public static <T, k, v> List<T> mapListToBeanList(List<Map<k, v>> listMap, Class<T> bean) {
		List<T> beanList = new ArrayList<T>(listMap.size());
		for (Map<k, v> map : listMap) {
			T t = null;
			try {
				BeanInfo beanInfo = Introspector.getBeanInfo(bean);
				PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
				t = bean.newInstance();
				for (PropertyDescriptor property : propertyDescriptors) {
					String key = property.getName();
					if (map.containsKey(key)) {
						Object value = map.get(key);
						Method setter = property.getWriteMethod();
						setter.invoke(t, value);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			beanList.add(t);
		}

		return beanList;
	}

	/**
	 * Convert Entities to Map s
	 * Convert key to underscore by hump rule (uppercase)
	 * @param bean
	 * @return
	 */
	public static Map<String, Object> beanToColumnMap(Object bean) {
		Class<?> type = bean.getClass();
		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(type);
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (int i = 0; i < propertyDescriptors.length; i++) {
				PropertyDescriptor descriptor = propertyDescriptors[i];
				String propertyName = descriptor.getName();
				if (!propertyName.equals("class")) {
					Method readMethod = descriptor.getReadMethod();
					Object result = readMethod.invoke(bean, new Object[0]);
					if (result != null && !result.equals("")) {
						returnMap.put(camelToUnderline(propertyName), result);
					}
				}
			}
		} catch (Exception e) {
			e.getMessage();
			// returnMap.put("error", e.getMessage());
			// returnMap = null;
		}
		return returnMap;
	}

	/**
	 * Convert camel Map to Column Map
	 * 
	 * @param bean
	 * @return
	 */
	public static Map<String, Object> camelMapToColumnMap(Map<String, Object> beanMap) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			for (String key : beanMap.keySet()) {
				returnMap.put(camelToUnderline(key), beanMap.get(key));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnMap;
	}

	/**
	 * String Underline To Camel
	 * 
	 * @param line
	 * @return
	 */
	public static String underlineToCamel(String line) {
		if (line == null || "".equals(line)) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		Pattern pattern = Pattern.compile("([A-Za-z\\d]+)(_)?");
		Matcher matcher = pattern.matcher(line);
		while (matcher.find()) {
			String word = matcher.group();
			Character c = word.charAt(0);
			sb.append(matcher.start() == 0 ? Character.toLowerCase(c) : Character.toUpperCase(c));
			int index = word.lastIndexOf('_');
			if (index > 0) {
				sb.append(word.substring(1, index).toLowerCase());
			} else {
				sb.append(word.substring(1).toLowerCase());
			}
		}
		return sb.toString();
	}

	/**
	 * String Hump To Underline
	 * 
	 * @param line
	 * @return
	 */
	public static String camelToUnderline(String line) {
		if (line == null || "".equals(line)) {
			return "";
		}
		Character c = line.charAt(0);
		String f = line.substring(1);
		line = String.valueOf(c).toUpperCase().concat(f);
		StringBuffer sb = new StringBuffer();
		Pattern pattern = Pattern.compile("[A-Z]([a-z\\d]+)?");
		Matcher matcher = pattern.matcher(line);
		while (matcher.find()) {
			String word = matcher.group();
			sb.append(word.toUpperCase());
			sb.append(matcher.end() == line.length() ? "" : "_");
		}
		return sb.toString();
	}

}

impl code

 @Override
    public User selectList1(User user) {
        Map<String, Object> map = QueryEntityTools.beanToMap(user);
        return baseMapper.selectList1(map);
 }

mappper

@Mapper
public interface UserDao extends BaseMapper<User> {

    User selectList1(Map map);
}

xml

 <select id="selectList1" resultMap="BaseResultMap">
    select * from user where username= #{username} and phone=#{phone}
 </select>

perhaps

<select id="selectList1" resultMap="BaseResultMap" parameterType="java.util.Map">
   select * from user where username= #{username} and phone=#{phone}
</select>

Thank you for watching the grid, next time mybatis plus + Custom Template Generator

Topics: Programming Java JSON Apache xml