This article explains how to configure datasource in the JBoss application server and how to use the same datasource in the hibernate configuration file.Before looking into the hibernate configuration, we will start with creating datasource inside JBoss application server.
also read:
Create MySql datasource in JBoss
To create datasource for the MySql database inside the JBoss application server, you have to
first create mysql-ds.xml file with the following entries:
<datasources> <local-tx-datasource> <jndi-name>SampleDS</jndi-name> <connection-url>jdbc:mysql://localhost:3306/SampleDB</connection-url> <driver-class>com.mysql.jdbc.Driver</driver-class> <min-pool-size>1>/min-pool-size> <max-pool-size>20>/max-pool-size> <user-name>root>/user-name< <password>root</password> <metadata> <type-mapping>mySQL</type-mapping> </metadata> </local-tx-datasource> </datasource>
Put mysql-ds.xml file under jbossserverdefaultdeploy. JBoss application server will
automatically take this file and create the datasource for you. You need not restart the server. Creating datasource
is completed. Next we will look into the hibernate configuration file for maping this datasource.
Use datasource in Hibernate configuration
To map datasource in the hibernate configuration file is simple task and need not
specify anything other than the datasource name. You have to include the following two lines of code
in the configuration file to tell the hibernate container to use datasouce for retrieving the new
connection from the databse.
<property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="connection.datasource">SampleDS</property>
Now we have configured datasource and mapped to the hibernate configuration file. All the connection
from the hibernate will be retrieved from datasource instead of directly from the database. This approach is
most widely used for the application development.
mysql-ds.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- $Id: mysql-ds.xml 63175 2007-05-21 16:26:06Z rrajesh $ --> <!-- Datasource config for MySQL using 3.0.9 available from: http://www.mysql.com/downloads/api-jdbc-stable.html --> <datasources> <local-tx-datasource> <jndi-name>SampleDS</jndi-name> <connection-url>jdbc:mysql://localhost:3306/SimpleDB</connection-url> <driver-class>com.mysql.jdbc.Driver</driver-class> <min-pool-size>1</min-pool-size> <max-pool-size>20</max-pool-size> <user-name>root</user-name> <password>root</password>--> <metadata> <type-mapping>mySQL</type-mapping> </metadata> </local-tx-datasource> </datasource>
hibernate.cfg.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="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="connection.datasource">SampleDS</property> </session-factory> </hibernate-configuration>