我希望表位于不同的数据库模式中。但不幸的是,我无法用 Spring Boot 实现这一点。这里是重现它的步骤。
在 http://start.spring.io 上创建一个新的 Spring Boot 项目版本 2.0.5(具有 derby 和 PostgreSQL 依赖项)
创建简单实体
@Entity
@Table(name = "my_table")
public class MyTable {
@Id Integer id;
}
- 仅将下一个属性添加到 application.properties,值为“update”或“create”(如果您尝试“create-drop”,则会出现此处描述的另一个错误:https://github.com/spring-projects/spring-boot/issues/7706#issuecomment-268798059)。现在将默认使用 Derby 数据源。
spring.jpa.hibernate.ddl-auto=create
运行生成的测试或主类。确保一切正常。
修改实体,在
@Table
注解中添加属性schema
。现在实体看起来像:
@Entity
@Table(name = "my_table", schema = "my_schema")
public class MyTable {
@Id Integer id;
}
- 运行测试(或主类)。这次我在 Spring Boot 初始化过程中遇到错误“
java.sql.SQLSyntaxErrorException: Schema 'MY_SCHEMA' does not exist
”:
此处提供完整的日志列表:https://gist.github.com/asaushkin/8d767c92b2e7025dd359f7be43eefdd6
- 检查 PostgreSQL。此错误也会在 PostgreSQL 实例上重现。没有 'schema' 属性,Spring Boot 应用程序运行完美,但只要此属性出现在 @Table 注释上,就会抛出异常。
完整日志在这里:https://gist.github.com/asaushkin/dd0d677964556bf943c4f013d4785372
我的问题是:为什么模式不是由 Spring Boot 创建的?
这些选项也不能解决这个问题:
spring.jpa.properties.javax.persistence.schema-generation.create-database-schemas=true
spring.jpa.properties.hibernate.hbm2dll.create_namespaces=true
链接
- https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl
- https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html#howto-configure-jpa-properties
更新(2019 年 3 月 11 日):
我刚刚检查了问题的当前行为。我想知道,但目前使用 Derby 驱动程序一切正常,并且表是使用指定的模式创建的。但是在 PostgreSQL 中仍然存在错误。
生成的 SQL(对于 PostgreSQL)是:
create table my_schema.my_table (id int4 not null, primary key (id))
最佳答案
检查您是否在 application.properties 文件中指定了数据库方言,或没有更多检查此线程。
Unable to get spring boot to automatically create database schema
关于java - Spring Boot 应用程序不会为 JPA @Table 注释创建模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52296215/