开发者

How to manage connection to database?

开发者 https://www.devze.com 2023-03-13 07:28 出处:网络
I should manage a connection to a database from my web application (Tomcatserver/frameworkJSF) ,theconnection from my login pageuntil the deconnection.

I should manage a connection to a database from my web application (Tomcatserver/frameworkJSF) ,theconnection from my login page until the deconnection. I have found that I should let the container manage the connection/deconnection to the database but the ex开发者_如何学编程ample that I found show how to configure tomcat server (http://christophej.developpez.com/tutoriel/j2ee/pooltomcat/)and use the connection from a servlet but I want to use the connection from my beans. how can I instanciate a connection in my classess each time without creation of a new connection?


You create a datasource in Tomcat or somewhere else which is a pool of connections. You take a connection from that pool and then release it when you're done with it. Tomcat example (in context.xml):

<Resource auth="Container" driverClassName="com.mysql.jdbc.Driver"
        maxActive="100" maxIdle="30" maxWait="10000" name="jdbc/yourname"
        password="..." type="javax.sql.DataSource"
        url="jdbc:mysql://localhost:3306/mydb?characterEncoding=utf8"
        username="..."/>

This creates a pool with a JNDI name 'jdbc/yourname'. You can get this from Spring like this:

<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/yourname" />

This will create a DataSource object that you can inject into your Java code as needed.

Or there are plenty of JNDI lookup examples on the web to do this programmatically instead of declaratively.

There are also loads of pool implementations, like c3po.

0

精彩评论

暂无评论...
验证码 换一张
取 消