英文:
Is it possible to make Spring Boot JPA Hibernate application to automatically create tables with necessary columns and relations from JPA entities?
问题
我是一个只懂得Java核心基础的新手。我有一个测试任务,需要使用Spring Boot创建一个简单的REST Web服务。
我已经在Java核心中编写了所有逻辑,现在我尝试将它包装在所有这些技术中。
我正在使用这个指南:
https://spring.io/guides/tutorials/rest/
在这里,他们有JPA实体和@table注解,其中指定了表名,但是在这个指南中没有SQL脚本来创建表。
所以我想JPA会自己创建实体的数据库和表,但是当我取消注释@table注解时,它显示"无法解析表'<table_name>'"。
我正在使用带有已导入的Spring Web、H2和JPA的Spring Boot Maven项目(就像指南中所说的那样)。
我还配置了H2数据源并测试了连接:一切正常。有一个模式,但没有表。
这是我的application.properties:
spring.h2.console.enabled=true
spring.h2.console.path=/h2_console
spring.datasource.url=jdbc:h2:~/kaylemains
spring.datasource.platform=h2
spring.datasource.initialization-mode=always
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.generate-ddl=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
就像在指南中一样,我在LoadDatabase类中添加实体,如下所示:
@Bean
CommandLineRunner initTournaments(TournamentRepository repository) {
return args -> {
log.info("Preloading " + repository.save(new Tournament("Kayle Mains Competition: Summoner's Gorge", 16)));
};
}
所以我的问题是:我是否可以拥有存储在文件中的H2数据库,并且可以从我的Java代码中执行所有操作(包括表的创建)?
还是必须手动创建表(通过编写带有CREATE TABLE的SQL脚本),并且构建它们以使所有实体正常工作?(这意味着定义外键列等),之后JPA才能够与这个数据库一起使用?我需要为每个字段添加@Column注解,JPA不会自动为其实体添加吗?
为什么会出现"无法解析表"的错误?当然无法解析,因为它还不存在,我以为JPA和Hibernate会根据实体类为我创建它...
英文:
I am a newbie that only knows basics of Java Core. I have test task where I need to create simple REST Web Service with Spring Boot.
I wrote all the logic in Java Core, and now I try to wrap it in all these technologies.
I am using this guide:
https://spring.io/guides/tutorials/rest/
Here they have JPA entities and @Table annotation, where table name is specified, but there are no SQL scripts to create tables in this guide.
So I thought JPA will create database and tables for entities by itself, but when I uncomment @Table annotation it says "Cannot resolve table '<table_name>'"
I am using IntelliJ IDEA with Spring Boot Maven project with imported Spring Web, H2 and JPA (like the guide tells to do).
I also configured H2 Data Source and tested the connection: works fine. There is a schema, but no tables.
Here is my application.properties:
spring.h2.console.enabled=true
spring.h2.console.path=/h2_console
spring.datasource.url=jdbc:h2:~/kaylemains
spring.datasource.platform=h2
spring.datasource.initialization-mode=always
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.generate-ddl=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
As in the guide, I add entities in LoadDatabase class like this:
@Bean
CommandLineRunner initTournaments(TournamentRepository repository) {
return args -> {
log.info("Preloading " + repository.save(new Tournament("Kayle Mains Competition: Summoner's Gorge", 16)));
};
}
So my question is: can I have file-stored H2 database and do everything with the it (including table creation) from my Java code?
OR it is necessary to create tables manually (by writing SQL scripts with CREATE TABLE) and construct them so that all entities work fine? (that means defining foreign key columns etc.), and only after that will JPA be able to work with this database? Do I need to add @Column annotation to every field, and JPA won't do it by itself for its Entities?
Why am I getting this error of "Cannot resolve table"? Of course it cannot be resolved because it does not exist yet, I thought JPA & Hibernate will create it for me based on entity classes...
答案1
得分: 3
这里在Baeldung网站上,你可以找到关于DDL生成的属性的所有信息。
Spring提供了一个专门用于Hibernate DDL生成的JPA属性:spring.jpa.hibernate.ddl-auto。
create – Hibernate首先删除现有表,然后创建新表。
update – 基于映射(注解或XML)创建的对象模型会与现有架构进行比较,然后Hibernate根据差异更新架构。即使应用程序不再需要现有的表或列,它也不会删除它们。
create-drop – 类似于create,额外的是Hibernate会在所有操作完成后删除数据库。通常用于单元测试。
validate – Hibernate仅验证表和列是否存在,否则会抛出异常。
none – 这个值有效地关闭了DDL生成。
我们必须谨慎设置这个值,或者使用其他机制来初始化数据库。
如果问题仍然存在,请转到“设置” -> “检查”,然后取消选中“未解析的数据库引用注释”选项。
英文:
Here in Baeldung you have all the information about the properties to ddl generation
> Spring provides a JPA-specific property which Hibernate uses for DDL generation: spring.jpa.hibernate.ddl-auto.
>
>create – Hibernate first drops existing tables, then creates new tables
>
>update – the object model created based on the mappings (annotations or XML) >is compared with the existing schema, and then Hibernate updates the schema >according to the diff. It never deletes the existing tables or columns even if >they are no more required by the application
>
>create-drop – similar to create, with the addition that Hibernate will drop >the database after all operations are completed. Typically used for unit testing
> validate – Hibernate only validates whether the tables and columns exist, otherwise it throws an exception
>
>none – this value effectively turns off the DDL generation
>
> We have to set the value carefully or use one of the other mechanisms
> to initialize the database.
If the problem is still present go to Settings -> Inspections, and uncheck the option "Unresolved database references in annotation"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论