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
I have a column in my Database, called updateddate, which should get inserted with sysdate through application.
If my application code encounters some exception, even then I want this column value to be inserted with sysdate through database.
So, through SQL script, I have given this column default to sysdate.
Below is my hibernate hbm xml file,
<property name="updatedDate" type="timestamp">
<column name="UPDATED_DATE" ></column>
</property>
However, the column is not getting inserted through my application when there are no exceptions. It is getting updated through DB.
I am saying this by looking at the date format.
How to make the column to be inserted through application and only when it encounters exception it should get inserted through DB?
I tried insert=true. But didn't help.
I am not quite sure why you want to do this, but your application should set updatedDate to the current system date/time. The database default will only be applied if your application inserts a record with updatedDate = null.
I have such hibernate.cfg.xml:
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:postgresql://host:5432/app-dev</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="hbm2ddl.auto">validate</property>
...many mappings
</session-factory>
And the problem is that it's trying to update my database schema, but I want to disable that feature.
log from my application:
2015-08-29 16:29:57 ERROR SchemaUpdate:261 - HHH000388: Unsuccessful: create table myschema.public.mytable (id int4 not null, count int4, anotherid int4, onemoreid int4, primary key (id))
2015-08-29 16:29:58 ERROR SchemaUpdate:262 - ERROR: syntax error at or near "-" <<(mydatabase name contains "-" sign)
Position: 27
I also tried to leave hbm2ddl.auto tag empty or include 'none' value in it.
Remove the property <property name="hbm2ddl.auto">validate</property> entirely.
By default all options will be false and hibernate will not attempt to do any updates.
Remove Hibernatehbm2ddl.auto defaults to Hibernate not doing anything.
From the docs
The hbm2ddl.auto option turns on automatic generation of database
schemas directly into the database. This can also be turned off by
removing the configuration option, or redirected to a file with the
help of the SchemaExport Ant task.
Validate is the default property of hbm2ddl.auto, even if you dont specify hbm2ddl.auto property, then also it is by default validate. Secondly there is no such value as "none", there are only 4 options :
validate- it simply checks that table and its columns are existing in database or not an if a table does not exist or any column does not exist than Exception is thrown.
create - If the value is create than hibernate drops the table if it already exist and then creates a new table and executes the operation, this is not used in real time as the old data is lost from database.
update - If the values is update than hibernate uses existing table and if the table does not exist than creates a new table and executes operation. This is mostly and often used in real time and it is recommended.
create-drop - if the value is create-drop than hibernate creates a new table and after executing the operation it drops the table, this value is used while testing hibernate code.
Thanks
Njoy Coding
The DataApp included in the javafx demos example comes with an ant script to create and populate a database with MySQL. After configuring the MySql connector it is only a matter of calling an ant task:
<target name="-post-init" >
<input message="Please enter Mysql password for root#localhost:" addproperty="mysql.password"/>
<!-- first create user and database -->
<echo>Creating "dataapp" user and "APP" database...</echo>
<sql driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:4447/mysql"
userid="root"
password="mysql-connector-java-5.1.18.jar"
classpath="${libs.MySQLDriver.classpath}"
>
DELETE FROM user WHERE User = 'dataapp';
DELETE FROM db WHERE User = 'dataapp';
INSERT INTO user VALUES ('localhost','dataapp','*B974A83D18BB105D0C9186756F485406E6E6039B','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','',0,0,0,0,'',NULL);
INSERT INTO db VALUES ('localhost','APP','dataapp','Y','Y','Y','Y','Y','Y','N','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','N','Y');
DROP DATABASE IF EXISTS APP;
CREATE DATABASE APP;
FLUSH PRIVILEGES;
</sql>
<echo>Creating tables and views...</echo>
<sql driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/APP"
userid="dataapp"
password="dataapp"
classpath="${libs.MySQLDriver.classpath}"
src="${basedir}/create-database.sql"/>
<echo>Populating zip code table(this might take a little while)...</echo>
<sql driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/APP"
userid="dataapp"
password="dataapp"
classpath="mysql-connector-java-5.1.18.jar"
src="${basedir}/zip_code_inserts.sql"/>
</target>
However, I am getting this exception when I run it:
[sql] Failed to execute: INSERT INTO user VALUES ('localhost','dataapp','*B974A83D18BB105D0C9186756F485406E6E6039B','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','',0,0,0,0,'',NULL)
With this exception:
java.sql.SQLException: Column count doesn't match value count at row 1
I think that the number of fields is not what it should be, but I am no MySQL expert, so I don't know how to fix this. Any help would be appreciated.
The number of columns that the 'user' table has seems to change from one version of MySQL to the next one. I was able to find the correct number by logging into the MySQL console, and do:
SELECT count(*) FROM information_schema.`COLUMNS` WHERE table_name = 'user' AND TABLE_SCHEMA = 'mysql';
Then I used:
SELECT * FROM user;
to see what where the values for my own user and copy those, the correct command for:
Server version: 5.1.61-community-log
was:
INSERT INTO user VALUES ('localhost','dataapp','*B974A83D18BB105D0C9186756F485406E6E6039B','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');
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.