通过反射获取Hibernate实体字段名

Hibernate实体形如:
	/** 用户名 */
	private String userName;
	/** 密码 */
	private String password;
	/** 用户类型 */
	private String typeId;
	/** 用户状态 */
	private String status;

	@Column(name = "USER_NAME", nullable = false, length = 36)
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	@Column(name = "PASSWORD", nullable = false, length = 32)
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Column(name = "TYPE_ID", nullable = false, length = 10)
	public String getTypeId() {
		return typeId;
	}

	public void setTypeId(String typeId) {
		this.typeId = typeId;
	}

	@Column(name = "STATUS", nullable = false, length = 10)
	public String getStatus() {
		return status;
	}
获取所有字段的方法
	/**
	 * <pre>
	 * 获取实体所有字段
	 * @param clazz 实体类型
	 * @param strs 需要排除的字段
	 * @return Map<String, Method> 其中key为数据库字段名称,value为字段对应的get方法
	 * 2011-4-23 下午01:52:06
	 * </pre>
	 */
	public static Map<String, Method> getFields(Class<?> clazz, List<String> strs) {
		Map<String, Method> map = new HashMap<String, Method>();
		Method[] methods = clazz.getMethods();
		for (Method method : methods) {
			Column c = method.getAnnotation(Column.class);
			if (null!=strs&&strs.contains(c.name())) {
				continue;
			}
			if (null != c) {
				map.put(c.name(), method);
			} else {
				JoinColumn jc = method.getAnnotation(JoinColumn.class);
				if (null!=strs&&strs.contains(jc.name())) {
					continue;
				}
				if (null != jc) {
					map.put(jc.name(), method);
				}
			}
		}
		return map;
	}

猜你喜欢

转载自shewolfep.iteye.com/blog/1013390