67,515
社区成员
发帖
与我相关
我的任务
分享
package com.feinno.model.user;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "USER_INFO", schema = "CDB")
public class User implements java.io.Serializable {
private Long id;
private String username;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="ID")
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "USERNAME", length = 20)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
}
private static boolean isPrimaryKeyProperty(PropertyDescriptor pd) {
Method getter = pd.getReadMethod();
if(getter != null && getter.isAnnotationPresent(Id.class)) {
return true;
}
Method setter = pd.getWriteMethod(); // 这里在上一楼写错了
if(setter != null && setter.isAnnotationPresent(Id.class)) {
return true;
}
return false;
}
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.persistence.Entity;
import javax.persistence.Id;
public class Test {
public static void main(String[] args) throws Exception {
PropertyDescriptor pd = getPrimaryKeyPropertyDescriptor(User.class);
System.out.println(pd.getDisplayName());
}
public static PropertyDescriptor getPrimaryKeyPropertyDescriptor(Class<?> clazz) {
if(clazz == null) {
return null;
}
if(!clazz.isAnnotationPresent(Entity.class)) {
throw new IllegalArgumentException("is not Entity");
}
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class);
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for(int i = 0; i < pds.length; i++) {
PropertyDescriptor pd = pds[i];
// Id 标注在方法上
if(isPrimaryKeyProperty(pd)) {
return pd;
}
// Id 标注在字段上
if(isPrimaryKeyField(pd, clazz)) {
return pd;
}
}
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
private static boolean isPrimaryKeyProperty(PropertyDescriptor pd) {
Method getter = pd.getReadMethod();
if(getter != null && getter.isAnnotationPresent(Id.class)) {
return true;
}
Method setter = pd.getReadMethod();
if(setter != null && setter.isAnnotationPresent(Id.class)) {
return true;
}
return false;
}
private static boolean isPrimaryKeyField(PropertyDescriptor pd, Class<?> clazz)
throws Exception {
Field field = clazz.getDeclaredField(pd.getName());
if(field.isAnnotationPresent(Id.class)) {
return true;
}
return false;
}
}