qxl*_*lab 2 java reflection annotations jpa
@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;
Run Code Online (Sandbox Code Playgroud)
如何使用反射从 POJO 中获取使用javax.persistence.Id
注释定义的主键列名称?我必须找到@Id
然后获取注释name
的属性@Column
...我不知道该怎么做...
谢谢!
这是您自己的解决方案:
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;
}
Run Code Online (Sandbox Code Playgroud)
请注意:这不适用于复合主键。
归档时间: |
|
查看次数: |
4724 次 |
最近记录: |