项目中使用 Hibernate JPA, 需求是根据 Entity的java 类,来获取所有的对应的数据库字段。
直接上代码。
用户类,对应数据库的user表
import org.hibernate.validator.constraints.NotBlank;
import javax.persistence.*;
import javax.validation.constraints.Size;
import java.util.Date;
@Entity
@Table(name = "my_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@Size(max=255)
@NotBlank
private String name;
@Size(max=255)
private String account;
private Integer age;
private Date birthday;
@Column(name = "my_hope")
private String myHope;
... //省略setter getter方法
}
通过JPA的EntityManagerFactory可以找到项目中所有的Entity,然后输出用jpa提供的方法找到每一个Entity对应的表名和字段名。
//通过EntityManager获取factory
EntityManagerFactory entityManagerFactory = (你自己的entityManager对象).getEntityManagerFactory();
SessionFactoryImpl sessionFactory = (SessionFactoryImpl)entityManagerFactory.unwrap(SessionFactory.class);
Map<String, EntityPersister> persisterMap = sessionFactory.getEntityPersisters();
for(Map.Entry<String,EntityPersister> entity : persisterMap.entrySet()){
Class targetClass = entity.getValue().getMappedClass();
SingleTableEntityPersister persister = (SingleTableEntityPersister)entity.getValue();
Iterable<AttributeDefinition> attributes = persister.getAttributes();
String entityName = targetClass.getSimpleName();//Entity的名称
String tableName = persister.getTableName();//Entity对应的表的英文名
System.out.println("类名:" + entityName + " => 表名:" + tableName);
//属性
for(AttributeDefinition attr : attributes){
String propertyName = attr.getName(); //在entity中的属性名称
String[] columnName = persister.getPropertyColumnNames(propertyName); //对应数据库表中的字段名
String type = "";
PropertyDescriptor targetPd = BeanUtils.getPropertyDescriptor(targetClass, propertyName);
if(targetPd != null){
type = targetPd.getPropertyType().getSimpleName();
}
System.out.println("属性名:" + propertyName + " => 类型:" + type + " => 数据库字段名:" + columnName[0]);
}
}
最后可以看到User类的输出为:
类名:User => 表名:my_user
属性名:account => 类型:String => 数据库字段名:account
属性名:age => 类型:Integer => 数据库字段名:age
属性名:birthday => 类型:Date => 数据库字段名:birthday
属性名:myHope => 类型:String => 数据库字段名:my_hope
属性名:name => 类型:String => 数据库字段名:name