If I have two session factory , it means I am using two DB schema in my application, so is it required two config file?
You only need one config file. Just add multiple session-factories like this:
<session-factory name="firstdatasource">
<property name="datasource">my/first/datasource</property>
<mapping resource="..."/>
..
</session-factory>
<session-factory>
<property name="datasource">seconddatasource</property>
..
</session-factory>
Related
I am new bee to Hibernate and trying out things.
One thing that seems to amuse all is how to connect to different databases?
I have two questions here:
If in the same web app I need to connect to MySQL and Oracle, how do I do it?
I am using MySQL and have two databases test1 and test2, how to connect and retrieve data?
I have read in a blog that we can create different configuration files and do it.
I tried it but was not sucessful.
Here's what I tried:
SessionFactory sf = (SessionFactory) new Configuration().configure(path);
Where path is the path of the config file.
Is this the right way?
Using annotation mappings as an example:
Configuration cfg1 = new AnnotationConfiguration();
cfg1.configure("/hibernate-oracle.cfg.xml");
cfg1.addAnnotatedClass(SomeClass.class); // mapped classes
cfg1.addAnnotatedClass(SomeOtherClass.class);
SessionFactory sf1 = cfg1.buildSessionFactory();
Configuration cfg2 = new AnnotationConfiguration();
cfg2.configure("/hibernate-mysql.cfg.xml");
cfg2.addAnnotatedClass(SomeClass.class); // could be the same or different than above
cfg2.addAnnotatedClass(SomeOtherClass.class);
SessionFactory sf2 = cfg2.buildSessionFactory();
Then use sf1 and sf2 to get the sessions for each database. For mapping files, you just use cfg.addClass instead of addAnnotatedClass. Put the cfg.xml files in the root package in this case. Those will have the Oracle or MySQL dialect and connection information.
It cannot be done using one hibernate configuration file. You need to have two configurations files for it.
To configure mysql database
hibernate-mysql.cfg.xml
To configure oracle database
hibernate-oracle.cfg.xml
In Details, mysql configuration file be like this.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">PASSWORD</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/UR_DB_NAME</property>
<property name="hibernate.connection.username">USERNAME</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="domain.EmployeeMysql"></mapping>
</session-factory>
</hibernate-configuration>
In Details, oracle configuration file be like this.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">PASSWORD</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:UR DB NAME</property>
<property name="hibernate.connection.username">USERNAME</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<mapping class="domain.EmployeeOracleSql"></mapping>
</session-factory>
</hibernate-configuration>
And code should be like this.
mysql configuration
private static SessionFactory sessionAnnotationFactory;
sessionAnnotationFactory = new Configuration().configure("hibernate-mysql.cfg.xml").buildSessionFactory();
Session session = sessionAnnotationFactory.openSession();
oracle sql configuration
sessionAnnotationFactory = new Configuration().configure("hibernate-oracle.cfg.xml").buildSessionFactory();
Session session = sessionAnnotationFactory.openSession()
Ideally you should move to Distributed transaction type of system[using Java Transaction Analyzer org.hibernate.transaction.JTATransactionFactory] in this case. If you are running in JBoss App Server, you can do it by using "Distributed Transaction Managers". You can learn more about it here.
You can also use a catalog with the value of the other database
#Table(name = "foo", schema = "bar", catalog = "OtherDatabase")
You can also Add mapping class in configuration.xml file
Note : this is for annotations and for resources use resources keyword instead of class
<mapping class="packageName.classNmae1"/>
<mapping class="packageName.classNmae2"/>
You can connect two databases test1 and test2, retrieve data with only one hibernate with some tricks:
hibernate SQLQuery: just add database name with the table "select * from test1.table1", "select * from test2.table2"
hibernate persistence: using the key schema in the hibernate mapping xml
<class name="Table1Class" table="table1" schema="test1">
<class name="Table2Class" table="table2" schema="test2">
i develop a J2EE application with Hibernate, and i want to have 2 database, the first will be local (in client computer ), and the second will be in the server.
indeed , i want to configure hibernate to connect in the local databases when the global is not accessible.
My actual config file :
<hibernate-configuration >
<session-factory>
<property name= "hibernate.dialect"> org.hibernate.dialect.MySQLDialect</property>
<property name= "hibernate.connection.driver_class"> com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/serverBdd </property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="hibernate.connection.password"></property>
<mapping resource="hibernateConfiguration/Usine.hbm.xml"/>
<mapping resource="hibernateConfiguration/Produit.hbm.xml"/>
<mapping resource="hibernateConfiguration/Machine.hbm.xml"/>
<mapping resource="hibernateConfiguration/Operation.hbm.xml"/>
<mapping resource="hibernateConfiguration/Utilisateur.hbm.xml"/>
</session-factory>
</hibernate-configuration>
how Can i do this ? and if i can't what should i do to solve my problem ?
thanks
Sure, here you can find an example that writes in 2 databases at same time, but with a simple if condition you can decide which to use:
First, create 2 hibernate.cfg.xml files as usual but with different names
serverconfig.cfg.xml
localconfig.cfg.xml
After, in your DAO or wherever you get your hibernate Session simply check if server database and if it is not available use local configuration:
SessionFactory sessionFactory = new Configuration().configure("serverconfig.cfg.xml").buildSessionFactory();
if (sessionFactory == null)
sessionFactory = new Configuration().configure("localconfig.cfg.xml").buildSessionFactory();
Also, if you use Hibernate 4 or later check this answer
I have a Java EE Hibernate project, and I'm using MySQL as a database.
I want that when I first time run the project, it will create the database automatically.
This is my hibernate.cnf.xml:
<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/InternetProject</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">10</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping class="entities.Business" />
<mapping class="entities.Coupon" />
<mapping class="entities.User" />
<mapping class="entities.LastLogin" />
</session-factory>
</hibernate-configuration>
When I first time run this project on another computer, how can I make the database InternetProject to be created?
According to the config file, it might already do it and I'm not aware to it.
Thanks in advance.
<property name="hibernate.hbm2ddl.auto">create</property>
will create tables. But it will not create database. Change the connection url to generate the database.
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/InternetProject?createDatabaseIfNotExist=true</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">10</property>
Update : character encoding when creating database
<property name="connection.url">
jdbc:mysql://localhost/InternetProject?createDatabaseIfNotExist=true&useUnicode=yes&characterEncoding=UTF-8
</property>
<property name="hibernate.hbm2ddl.auto">create</property>
will do
Hibernate will not create the database for you, only the tables. To create the database you need to tell MySQL to create it if it does'nt already exist by adding a parameter to the URL. E.g.:
jdbc:mysql://db:3306/mydatabase?createDatabaseIfNotExist=true
There are multiple option for auto property.
create - It creates new tables corresponding mapping or annotation. It drops existing tables and data.
update - It keeps existing data and tables. It updates schema. here we have to take care contrants.
create-drop - It is same like create but once session gets closed it drops everything.
validate - it validates or matches schema with map or annotation. It's valid for Production environment.
<!-- create create-drop validate update -->
<property name="hbm2ddl.auto">update</property>
I hope it helps.
After few years of PHP I decided to learn Java, so I'm writing simple desktop app that uses Hibernate and SQLite.
I'd like to keep database outside of the .jar generated by mvn package, so one can perform quick backup of the data just by copying one file. So far, my hibernate.cfg.xml looks like this:
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="connection.url">jdbc:sqlite:mydb.db</property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.ex3v.hibernate.Contact"/>
</session-factory>
</hibernate-configuration>
what connection.url do I have to specify to make hibernate create db file next to .jar in working directory?
You can find your answer here:
Just a summary from above site,
different formats are :
jdbc:sqlite:mydb.db
jdbc:sqlite://dirA/dirB/mydb.db
jdbc:sqlite:/DRIVE:/dirA/dirB/mydb.db
jdbc:sqlite:///COMPUTERNAME/shareA/dirB/mydb.db
Use relative path like this.
jdbc:sqlite:./DB/mydb.db
I want to use HibernateOGM to interact with MongoDB. I have an cfg.xml file like this:
<hibernate-configuration>
<session-factory>
<property name="hibernate.transaction.factory_class">org.transaction.JDBCTransactionFactory</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.ogm.datastore.provider">mongodb</property>
<property name="hibernate.ogm.datastore.grid_dialect">org.hibernate.ogm.dialect.MongoDBDialect</property>
<property name="hibernate.ogm.mongodb.database">rcfdb</property>
<property name="hibernate.ogm.mongodb.host">127.0.0.1</property>
<property name="hibernate.ogm.mongodb.port">27017</property>
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<mapping resource="hibernate-contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I have also wrote my POJO class, and in the main class I want to populate the database in the mongodb with this code, but I am not able to do this job and I get these line of Infos, how can I solve that:
Session session=null;
OgmConfiguration cfgogm=new OgmConfiguration();
SessionFactory sessionfactory= cfgogm.buildSessionFactory();
session=sessionfactory.openSession();
session.beginTransaction();
System.out.println("Populating the database...");
Contact cnt=new Contact();
cnt.setFirstname("Blabla");
cnt.setLastname("Blabla");
cnt.setEmail("blabla");
session.save(cnt);
session.getTransaction().commit();
System.out.println("Done... :)");
I have no output with this code, and also no exceptions
INFO Lines:
This is the structure of my project:
You have specified MongoDBDialect in the configuration file. But on the console log, you are getting NoopDialect on HHH000400.
And in the next line, you are getting connection was null.
And the last line is, Unable to create requested service.
hibernate.ogm.mongodb.port -> hibernate.ogm.datastore.port
I puzzled over this for two days