Spring Boot JPA中使用@Entity和@Table的實(shí)現(xiàn)
本文中我們會(huì)講解如何在Spring Boot JPA中實(shí)現(xiàn)class和數(shù)據(jù)表格的映射。
默認(rèn)實(shí)現(xiàn)
Spring Boot JPA底層是用Hibernate實(shí)現(xiàn)的,默認(rèn)情況下,數(shù)據(jù)庫(kù)表格的名字是相應(yīng)的class名字的首字母大寫。命名的定義是通過接口ImplicitNamingStrategy來定義的:
/** * Determine the implicit name of an entity’s primary table. * * @param source The source information * * @return The implicit table name. */ public Identifier determinePrimaryTableName(ImplicitEntityNameSource source);
我們看下它的實(shí)現(xiàn)ImplicitNamingStrategyJpaCompliantImpl:
@Override public Identifier determinePrimaryTableName(ImplicitEntityNameSource source) { if ( source == null ) { // should never happen, but to be defensive... throw new HibernateException( 'Entity naming information was not provided.' ); } String tableName = transformEntityName( source.getEntityNaming() ); if ( tableName == null ) { // todo : add info to error message - but how to know what to write since we failed to interpret the naming source throw new HibernateException( 'Could not determine primary table name for entity' ); } return toIdentifier( tableName, source.getBuildingContext() ); }
如果我們需要修改系統(tǒng)的默認(rèn)實(shí)現(xiàn),則可以實(shí)現(xiàn)接口PhysicalNamingStrategy:
public interface PhysicalNamingStrategy { public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment jdbcEnvironment); public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment jdbcEnvironment); public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment); public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment jdbcEnvironment); public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment jdbcEnvironment);}
使用@Table自定義表格名字
我們可以在@Entity中使用@Table來自定義映射的表格名字:
@Entity@Table(name = 'ARTICLES')public class Article { // ...}
當(dāng)然,我們可以將整個(gè)名字寫在靜態(tài)變量中:
@Entity@Table(name = Article.TABLE_NAME)public class Article { public static final String TABLE_NAME= 'ARTICLES'; // ...}
在JPQL Queries中重寫表格名字
通常我們?cè)贎Query中使用JPQL時(shí)可以這樣用:
@Query(“select * from Article”)
其中Article默認(rèn)是Entity類的Class名稱,我們也可以這樣來修改它:
@Entity(name = 'MyArticle')
這時(shí)候我們可以這樣定義JPQL:
@Query(“select * from MyArticle”)
到此這篇關(guān)于Spring Boot JPA中使用@Entity和@Table的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Spring Boot JPA使用@Entity和@Table內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Kotlin + Flow 實(shí)現(xiàn)Android 應(yīng)用初始化任務(wù)啟動(dòng)庫(kù)2. Gitlab CI-CD自動(dòng)化部署SpringBoot項(xiàng)目的方法步驟3. ajax請(qǐng)求添加自定義header參數(shù)代碼4. ASP基礎(chǔ)知識(shí)VBScript基本元素講解5. 使用python 計(jì)算百分位數(shù)實(shí)現(xiàn)數(shù)據(jù)分箱代碼6. 基于javascript處理二進(jìn)制圖片流過程詳解7. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作。”的詭異問題……8. 教你如何寫出可維護(hù)的JS代碼9. 使用Python和百度語音識(shí)別生成視頻字幕的實(shí)現(xiàn)10. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)
