Spring Boot JPA中使用@Entity和@Table的实现
本文中我们会讲解如何在SpringBootJPA中实现class和数据表格的映射。
默认实现
SpringBootJPA底层是用Hibernate实现的,默认情况下,数据库表格的名字是相应的class名字的首字母大写。命名的定义是通过接口ImplicitNamingStrategy来定义的:
/** *Determinetheimplicitnameofanentity'sprimarytable. * *@paramsourceThesourceinformation * *@returnTheimplicittablename. */ publicIdentifierdeterminePrimaryTableName(ImplicitEntityNameSourcesource);
我们看下它的实现ImplicitNamingStrategyJpaCompliantImpl:
@Override
publicIdentifierdeterminePrimaryTableName(ImplicitEntityNameSourcesource){
if(source==null){
//shouldneverhappen,buttobedefensive...
thrownewHibernateException("Entitynaminginformationwasnotprovided.");
}
StringtableName=transformEntityName(source.getEntityNaming());
if(tableName==null){
//todo:addinfotoerrormessage-buthowtoknowwhattowritesincewefailedtointerpretthenamingsource
thrownewHibernateException("Couldnotdetermineprimarytablenameforentity");
}
returntoIdentifier(tableName,source.getBuildingContext());
}
如果我们需要修改系统的默认实现,则可以实现接口PhysicalNamingStrategy:
publicinterfacePhysicalNamingStrategy{
publicIdentifiertoPhysicalCatalogName(Identifiername,JdbcEnvironmentjdbcEnvironment);
publicIdentifiertoPhysicalSchemaName(Identifiername,JdbcEnvironmentjdbcEnvironment);
publicIdentifiertoPhysicalTableName(Identifiername,JdbcEnvironmentjdbcEnvironment);
publicIdentifiertoPhysicalSequenceName(Identifiername,JdbcEnvironmentjdbcEnvironment);
publicIdentifiertoPhysicalColumnName(Identifiername,JdbcEnvironmentjdbcEnvironment);
}
使用@Table自定义表格名字
我们可以在@Entity中使用@Table来自定义映射的表格名字:
@Entity
@Table(name="ARTICLES")
publicclassArticle{
//...
}
当然,我们可以将整个名字写在静态变量中:
@Entity
@Table(name=Article.TABLE_NAME)
publicclassArticle{
publicstaticfinalStringTABLE_NAME="ARTICLES";
//...
}
在JPQLQueries中重写表格名字
通常我们在@Query中使用JPQL时可以这样用:
@Query(“select*fromArticle”)
其中Article默认是Entity类的Class名称,我们也可以这样来修改它:
@Entity(name="MyArticle")
这时候我们可以这样定义JPQL:
@Query(“select*fromMyArticle”)
到此这篇关于SpringBootJPA中使用@Entity和@Table的实现的文章就介绍到这了,更多相关SpringBootJPA使用@Entity和@Table内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。