jpa中用JAVA获取列名,Hibernate JPA 根据Java类获取对应数据库的表名和字段名称

本文展示了如何通过Hibernate JPA获取Entity类中映射到数据库的所有字段,包括表名和字段名,以User类为例进行详细解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中使用 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 persisterMap = sessionFactory.getEntityPersisters();

for(Map.Entry entity : persisterMap.entrySet()){

Class targetClass = entity.getValue().getMappedClass();

SingleTableEntityPersister persister = (SingleTableEntityPersister)entity.getValue();

Iterable 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值