使用反射从 POJO 获取 id 列名称
Get id column name from POJO, using reflection
@Entity
@Table(name="MY_TABLE")
public class MyTable{
@Id
@Column(name="MY_TABLE_ID")
@GeneratedValue(strategy = GenerationType.AUTO ,generator="SQ_MY_TABLE")
@SequenceGenerator(name="SQ_MY_TABLE", sequenceName="SQ_MY_TABLE")
private Long myTableId;
如何使用反射从我的 POJO 中获取使用 javax.persistence.Id
注释定义的主键列名称?我必须找到 @Id
然后得到 @Column
注释的 name
属性...我不知道该怎么做...
谢谢!
这是完全靠自己的解决方案:
public static String getPKColumnName(Class<?> pojo) {
if (pojo == null)
return null;
String name = null;
for (Field f : pojo.getDeclaredFields()) {
Id id = null;
Column column = null;
Annotation[] as = f.getAnnotations();
for (Annotation a : as) {
if (a.annotationType() == Id.class)
id = (Id) a;
else if (a.annotationType() == Column.class)
column = (Column) a;
}
if (id != null && column != null){
name = column.name();
break;
}
}
if (name == null && pojo.getSuperclass() != Object.class)
name = getPKColumnName(pojo.getSuperclass());
return name;
}
请注意:这不适用于复合主键。
@Entity
@Table(name="MY_TABLE")
public class MyTable{
@Id
@Column(name="MY_TABLE_ID")
@GeneratedValue(strategy = GenerationType.AUTO ,generator="SQ_MY_TABLE")
@SequenceGenerator(name="SQ_MY_TABLE", sequenceName="SQ_MY_TABLE")
private Long myTableId;
如何使用反射从我的 POJO 中获取使用 javax.persistence.Id
注释定义的主键列名称?我必须找到 @Id
然后得到 @Column
注释的 name
属性...我不知道该怎么做...
谢谢!
这是完全靠自己的解决方案:
public static String getPKColumnName(Class<?> pojo) {
if (pojo == null)
return null;
String name = null;
for (Field f : pojo.getDeclaredFields()) {
Id id = null;
Column column = null;
Annotation[] as = f.getAnnotations();
for (Annotation a : as) {
if (a.annotationType() == Id.class)
id = (Id) a;
else if (a.annotationType() == Column.class)
column = (Column) a;
}
if (id != null && column != null){
name = column.name();
break;
}
}
if (name == null && pojo.getSuperclass() != Object.class)
name = getPKColumnName(pojo.getSuperclass());
return name;
}
请注意:这不适用于复合主键。