JPA Entity于DB之间的映射
最近在捣鼓JPA和mysql,发现JPA的Entity class和DB的table,column之前的mapping一直没弄明白,记录下,以供后查:
首先,有两个概念:
- 逻辑名字(logical Name)
Java Entity和Attribute在JPA中的命名(明白在Java class中的名字可不是JPA中的名字,JPA很傲娇啊)
- 物理名字(Physic Name)
指的是逻辑名字映射到数据库后的名字,如你所想就是Table, Column的名字
另外,有三个策略:
- Implicit Naming Strategy
- Physical Naming Strategy
- Annotation
前者影响了Entity包括Atribute的逻辑名字(Logic Name);
后者影响了物理名字(Physic Name);
至于Annotation,它会影响Implicit Naming Strategy和Physical Naming Strategy。
如何决定一个Logical Name
首先,我其实不是很理解为啥JPA还要个Entity的逻辑名字,用Entity和Attribute的名字不就好了吗。
其实Implicit Naming Strategy的默认的策略:ImplicitNamingStrategyJpaCompliantImpl
也就是这么干的,它规定逻辑名字跟Entity和Attribute的名字是完全一样的。然而还有几个OOB的策略:
但是Logical Name也不是Implicit Naming Strategy说的就算的,如果规定了Annotation如@Table或是@Column就得按照Annotation来。
如何决定一个Physics Name
如果没有指定任何的Physical Naming Strategy,即使指定了Annotation,如@Table或是@Column, JPA会将Logical name小写作为Physical Name(也就是说你在DB中的表明都是小写的)。
但是我的表名是大写的怎么整?
- 指定Physical Naming Strategy
2. 是用Annotation
这就成了,因为PhysicalNameingStragegyStandardImpl会告诉JPA严格按照Annotation的配置来映射Physical Name