SpringDataJPA笔记(12)-Table注解详解
由于在实际使用中,有时候会遇到需要访问同一台服务器上别的数据库,但是又不想配置多数据源的情况,Table注解给我们提供了这种便利的操作
JPA在根据实体自动生成数据表关联的时候,如果实体类与其映射的数据库表名不同名时,则需要使用到Table注解来标注映射的表名,除此之外还可以指定表所属的数据库目录或模式
首先来看一下Table注解的属性
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String name() default "";
String catalog() default "";
String schema() default "";
UniqueConstraint[] uniqueConstraints() default {};
Index[] indexes() default {};
}
name
name属性用于指定数据库表名称
若不指定则以实体类名称作为表名
例如如下代码
@Entity
@Table
public class TableEntity extends AnimalEntity<Long> {
}
生成的数据库名为table_entity
catalog
catalog属性用于指定数据库实例名
一般来说数据库实例在数据源配置的时候指定了,不配置就默认使用数据源配置的默认库
如果使用catalog属性设置名称时,若数据库存在和指定名称一致的实例,新创建的表将出现在该实例中
若不存在,则会在启动的时候抛出异常
WARN 3304 --- [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "create table aaaadb.table_entity (id bigint not null auto_increment, age integer, gmt_create datetime not null, gmt_update datetime, height integer, name varchar(255), pid bigint, sex varchar(255), weight integer, primary key (id)) engine=InnoDB" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table aaaadb.table_entity (id bigint not null auto_increment, age integer, gmt_create datetime not null, gmt_update datetime, height integer, name varchar(255), pid bigint, sex varchar(255), weight integer, primary key (id)) engine=InnoDB" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.apply