简体   繁体   中英

How to use @Table JPA annotation for multiple database types?

I am working on a SCADA application that uses currently Microsoft SQL Server. My database looks like this:

在此处输入图像描述

I used InteliJ idea to generate Hibernate mapping using JPA annotations. The table annotation looks like this:

@Table(name = "EM_ANSI_POLL_DATA", schema = "dbo", catalog = "EMDB")

Now we need to use many different databases as per client requirement. We need to support MySql, Oracle and H2DB. This is confusing as there are different concepts for each database type. How can I make sure that same code works properly with each of above mentioned databases? How to port the database to MySQL, Oracle and H2DB without changing the Hibernate code?

Please note, I am using Spring boot. The entries in my application.properties look like this:

spring.datasource.url=jdbc:sqlserver://localhost;databaseName=EMDB
spring.datasource.username=sa
spring.datasource.password=*******
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto =none

If you use only one schema or/and catalog for the whole application, I guess it will be more flexible to put these settings in hibernate config:

<property name="hibernate.default_catalog" value="EMDB"/>
<property name="hibernate.default_schema" value="dbo"/>

and then it will be easy to change it for another database.

See also this .

Given that you are configuring the database via properties file, you should be able to connect to another database just by changing the properties.

For example, if you want to use H2 database this is the configuration:

spring.datasource.url=jdbc:h2:mem:EMDB
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=*********
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop # this is to auto-generate the database schema

And you also need to add the driver in the pom.xml file:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM