On Tomcat 6.x, Hibernate 3.x, MySQL, and JNDI 17
After lots of googling and documentation reading, I got a setup of mine to work properly with Tomcat 6.x, Hibernate 3.x, MySQL, and JNDI datasources. For what its worth, most of the resources on the web regarding setting this up with the versions I specified are worthless. To save myself the future hassle, and the lot of you who might be having a hard time setting this up, here are the configuration files and directives required.
yourapp/web/META-INF/context.xml:
<Context>
<Resource name="jdbc/my_app"
global="jdbc/my_app"
auth="Container"
type="javax.sql.DataSource"
username="user"
password="XXXX"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/my_db_name?autoReconnect=true"
maxActive="8"
maxIdle="4"/>
</Context>
yourapp/web/WEB-INF/web.xml:
... <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/my_app</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> ...
hibernate.cfg.xml:
...
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.datasource">java:comp/env/jdbc/my_app</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<mappings here>
</session-factory>
</hibernate-configuration>
...
You can get your session factory as usual:
sessionFactory = new Configuration().configure().buildSessionFactory();or whichever way you prefer.
Comments
-
Awesome stuff !!! I spent half a day trying to fix this issue. Very helpful post indeed.
-
I was completely stuck on the 'java:comp/env/jdbc/my_app' portion in the hibernate config. The Apache examples all put this in the Java code as a Context lookup and it is still missing the jdbc portion. Their example: DataSource ds = (DataSource) initCtx.lookup("java:comp/env/my-datasource") Keep on coding!!!
-
Really, gr8 help on hand stretch. Keep it up, Hisham
-
Thank you for the info. Excellent job!
-
Thank you VERY much! I've been hitting my head against the wall w/ this issue for the better part of a day - your post was exactly on point.
-
Thanks a lot for documenting this config. I was stuck for two days and finally your post got my project to work.
-
Thanks a lot.
-
Thanks for the info. After a lot of Googling I was able to find the very info I needed.
-
Short, concise, and above all correct! You've just saved me from another day of hair pulling. Cheers. :)
-
Thanks a lot. After a lot of attempts and googling I finally found the info I needed.
-
Thanks a lot for the code
-
Works! Thnx!!
-
Thanks a lot man...
-
great work ..really helpful..
-
Thank you very much. It helped to do my job in time
-
Thanks a lot. You have saved hell lot of our time. We appreciate that. :-)
-
Instead of writing JNDI config in application's context.xml file, cant we write this in application server context file? Please explain.