I need to know the simple steps to Access the Repository and Entity Classes from Multiple Databases.
Example: I have User table in DB1 and Email in DB2 have to access from a single Service Request.
DB 1
spring.datasource.url = jdbc:mysql://localhost:3306/dbName1?useSSL=false
spring.datasource.username = user
spring.datasource.password = password
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
DB 2
spring.datasource.url = jdbc:mysql://localhost:3306/dbName2?useSSL=false
spring.datasource.username = user
spring.datasource.password = password
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
OTHER PROPERTIES
spring.jpa.properties.hibernate.jdbc.batch_size=20
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true
spring.jpa.properties.hibernate.jdbc.batch_versioned_data=true
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
Solution 1:
You could create a user that has access to both databases and then use fully qualified table names when querying for the external table.
MySQL supports the dbname.tablename syntax to access tables outside the current database scope.
This requires that the currently connected user has the appropriate rights to read from the requested table in another physical db.
Solution 2:
You can configure two datasources as described here:
https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html#howto-two-datasources
(Not a direct answer.)
If you will be using text other than plain English, consider these settings:
Hibernate XML:
<property name="hibernate.connection.CharSet">utf8mb4</property>
<property name="hibernate.connection.characterEncoding">UTF-8</property>
<property name="hibernate.connection.useUnicode">true</property>
Connection url:
db.url=jdbc:mysql://localhost:3306/db_name?useUnicode=true&character_set_server=utf8mb4
#Table(name="tablename", catalog="db2")
worked for me
Related
Hei guys, im pretty new to SpringBoot and i have 1 problem.
When i start the app the spring read the schema.sql and make the tabels but the data.sql is not read, so i dont have no data on my db.
this is my app.prop
spring.datasource.url = jdbc:mysql://localhost:3306/garagesaledb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.format_sql = true
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.DefaultComponentSafeNamingStrategy
spring.jpa.hibernate.naming.physical-strategy= org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.sql.init.mode=always
spring.datasource.schema = classpath:db/schema.sql
spring.datasource.data = classpath:db/data.sql
spring.jpa.hibernate.ddl-auto=update
spring.liquibase.drop-first=true
spring.jpa.defer-datasource-initialization=true
schema.sql
create table asset
(
id bigint not null auto_increment,
category varchar(255),
price decimal(10,2),
quantity integer,
purchaseOrder_id bigint,
primary key(id),
);
data.sql
INSERT INTO garagesaledb.asset(category, price, quantity,purchaseOrder_id) VALUES
('MOUSE', 10.0, 1, null);
It's just a simple app and query but it doesnt read it.
Either you put the file somewhere outside the resources (external file) or provided the location wrongly, - please check the logs
To confirm that, change below line
spring.datasource.data = classpath:db/data.sql
to :
spring.datasource.data = file:<full-path>db/data.sql
OR
in some spring-boot versions,
spring.sql.init.data-locations=classpath:db/data.sql
Add this property to app.prop spring.datasource.initialization-mode=always
Refer Link : https://docs.spring.io/spring-boot/docs/2.1.0.M1/reference/html/howto-database-initialization.html#howto-initialize-a-database-using-spring-jdbc
Spring Boot automatically creates the schema of an embedded DataSource. This behaviour can be customized by using the spring.datasource.initialization-mode property. For instance, if you want to always initialize the DataSource regardless of its type:
spring.datasource.initialization-mode=always
I hope this helps.
I use spring-data-jpa and mysql database. My tables character set is utf-8. Also I added ?useUnicode=yes&characterEncoding=utf8 to mysql url in application.properties file. Problem when I pass characters like "ąčęėį" to controller to save it in mysql. In mysql I got ??? marks. But when I use mysql console example update projects_data set data="ąęąčę" where id = 1; every works well.
application.properties:
# "root" as username and password.
spring.datasource.url = jdbc:mysql://localhost:3306/gehive?useUnicode=yes&characterEncoding=utf8
spring.datasource.username = gehive
spring.datasource.password = pass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
tables:
+---------------+--------------------+
| TABLE_NAME | character_set_name |
+---------------+--------------------+
| customer | utf8 |
| projects | utf8 |
| projects_data | utf8 |
+---------------+--------------------+
Try
spring.datasource.url = jdbc:mysql://localhost:3306/gehive?useUnicode=yes&characterEncoding=UTF-8
It seems issue is due to missing "-".
Reference:-
https://forum.hibernate.org/viewtopic.php?f=1&t=1037497&view=next
I had the same issues, and I solved it by adding this line to my application.properties file:
spring.datasource.tomcat.connection-properties=useUnicode=true;characterEncoding=utf-8;
Note: The following didn't work:
spring.datasource.connectionProperties=useUnicode=true;characterEncoding=utf-8;
For anyone using the HikariCP connection pool who prefers not to append the parameters directly to the JDBC URL:
The spring.datasource.connectionProperties property was removed some time ago. Since then, you need to use connection pool specific properties as shown in #SebTheGreat's answer:
spring.datasource.tomcat.connection-properties=useUnicode=true;characterEncoding=utf-8;
Hikari doesn't have a connection-properties property, but this works:
spring.datasource.hikari.data-source-properties.useUnicode=true
spring.datasource.hikari.data-source-properties.characterEncoding=UTF-8
Remember to escape any special characters, as below:
spring.datasource.url=jdbc\:mysql\://localhost\:3306/${SERVER_DB_NAME}\?useUnicode=true\&characterEncoding=utf\-8\&characterSetResults=utf\-8
In my case that's solve my issue
https://mathiasbynens.be/notes/mysql-utf8mb4
[client]
default-character-set = utf8mb4
[mysql]
default-character-set = utf8mb4
[mysqld]
character-set-client-handshake = FALSE
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
It works for me if using mysql java connector version 5.1.44 (before I used connector 8.0.17 it doesn't work)
Another possible solution depending your configuration is using #SqlConfig annotation
#Sql(config = #SqlConfig(encoding = "utf-8"))
everyone, my app based on Spring MVC and i was trying to persist Arabic text in MySQL (i use JPA) but it's save ???? instead of Arabic characters. I tried to use this:
spring.datasource.url=jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8
but i got error when i tried to save text in Arabian:
java.sql.SQLException: Incorrect string value: '\xD8\xAA\xD8\xB1\xD8\xAD...' for column 'last_name' at row 1
Thanks in advance.
Hi after a bit of search in the internet I added a couple of lines to my application.properties in order to use UTF-8 encoding and it finally worked. here is the file. don't forget to change the url and password etc.
# DataSource settings: set here your own configurations for the
# #database
# connection. In this example we have "netgloo_blog" as database name #and
# "root" as username and password.
spring.datasource.url = jdbc:mysql://localhost:3306/newDB?useUnicode=yes&characterEncoding=UTF-8&characterSetResults=UTF-8
spring.datasource.username = root
spring.datasource.password = somePassword
# Keep the connection alive if idle for a long time (needed in #production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
server.tomcat.uri-encoding=UTF-8
# HTTP encoding (HttpEncodingProperties)
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the #prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen #database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.connection.characterEncoding=utf-8
spring.jpa.properties.hibernate.connection.CharSet=utf-8
spring.jpa.properties.hibernate.connection.useUnicode=true
server.port=8080
I am using EclipseLink JPA to connect to vertica database and fetch results. Before running the below piece of code
EntityManager em = ...
Query q = em.createQuery ("SELECT x FROM Table x");
List results = q.getResultList ();
I need to first run the "SET ROLES ALL" statement for the user id. How to run such statements in JPA.
Please guide me.
for Vertica, you can do two things:
set your default role for the user:
alter user myuser default role myrole;
use connection string property "ConnSettings" as described in the Vertica connection string docs (https://my.vertica.com/docs/6.1.x/HTML/index.htm#13173.htm):
A string containing SQL statements that the JDBC driver automatically
runs after it connects to the database. This property is useful to set
the locale, set the schema search path, or perform other configuration
that the connection requires.
Your connection string could look like something like this:
jdbc:vertica://myverticaserver/mydb?ConnSettings=SET+ROLE+myrole
I'm using Hibernate and a MySql server. I use multiple databases as "namespaces" (e.g. users, transactions, logging etc.).
So, I configued Hibernate to NOT connect to a particular database :
url = jdbc:mysql://127.0.0.1/
The databases where tables are located are defined in the hbm files through the catalog attribute :
<class name="com.myApp.entities.User" table="user" schema="" catalog="users"> ...
When I want to load some data, everything works fine and Hibernate seems to generate the expected SQL queries (by using the catalog prefix in the table names) e.g. :
select id from users.user
However, when I try to add a new record, Hibernate don't use the from [catalog].[table_name] syntax anymore. So I get a MySQL error 'No database selected'.
select max(id) from user
Hibernate is trying the get the future id to create a new record, but it doesn't specify in which database is located the table, it should be :
select max(id) from users.user
Why is Hibernate generating this invalid query ? Have someone ever experienced this problem ?
You need to specify the schema for the generator. See this question on SO for a more detailed answer.