jdbctemplateはクラス名でクエリー結果をエンティティオブジェクトにマッピングします(エンティティクラス属性はデータテーブルフィールド名と同じである必要があります)

3020 ワード

@SuppressWarnings("rawtypes")
	@RequestMapping(value = "openDetail")
	public String openDetail(NodeDetail nodeDetail, HttpServletRequest request, HttpServletResponse response, 
			RedirectAttributes redirectAttributes, Model model) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
		String discription = dictDao.getData("zljlqd",nodeDetail.getBillTypeID()).getDescription();
		String tableName = discription.split("&")[0];
		String viewName = dictDao.getData("zljlqd",nodeDetail.getBillTypeID()).getRemarks().split("&")[0];
		String id = nodeDetail.getDjid();
		String sql  =  "select * from "+tableName+" where id= ?";
		String baseurl = "com.jeeplus.modules.nodedetail.entity.";
		String classname = discription.split("&")[1];
		final Class clazz = Class.forName(baseurl+classname); 
		JdbcTemplate jdbcTemplate = getJdbcTemplate();
		Object object = jdbcTemplate.queryForObject(sql, new RowMapper(){
			@Override
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException{
				Field[] fileds = clazz.getDeclaredFields();
				Method [] methods = clazz.getDeclaredMethods();
				Object obj = null;
					try {
						obj = clazz.newInstance();
						for (int i = 0; i < fileds.length; i++) {
							String method = "set"+(fileds[i].getName().substring(0, 1).toUpperCase() + fileds[i].getName().substring(1));
							for (int j = 0; j < methods.length; j++) {
								if(method.equals(methods[j].getName())){
									String type  = fileds[i].getType().getName();
									@SuppressWarnings("unchecked")
									Method addMethod = clazz.getMethod(method, fileds[i].getType());
									if(isExistColumn(rs,fileds[i].getName())){
										if (type.equals("java.lang.Integer")) {
											addMethod.invoke(obj, rs.getInt(fileds[i].getName()));
										} else if (type.equals("java.lang.String")) {
											addMethod.invoke(obj, rs.getString(fileds[i].getName()));
										} else if (type.equals("java.util.Date")) {
											addMethod.invoke(obj, rs.getDate(fileds[i].getName()));
										}
									}
								}
							}
						}
					} catch (InstantiationException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (NoSuchMethodException e) {
						e.printStackTrace();
					} catch (SecurityException e) {
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					}
				return obj;
			}
		}, id);
		model.addAttribute(classname, object);
		model.addAttribute("noticeStatu", nodeDetail.getNoticeStatu());
		model.addAttribute("nodeDetailId", nodeDetail.getId());
		model.addAttribute("noticeId", nodeDetail.getNoticeId());
		return "modules/nodedetail/"+viewName;
	}