【Java】Spring和Tomcat自帶的連線池實現資料庫操作
前面我們已經用 Spring-Jdbc-CRUD%2F" rel="nofollow,noindex">Spring和傳統的Jdbc實現資料庫操作 、 Spring和JdbcTemplate實現資料庫操作 。但是這些都是基於 直連的資料來源 進行的,現在我們將介紹基於 連線池的資料來源 進行資料庫操作。前面幾個步驟都相同。
建立資料庫
首先建立我們的資料庫(這裡我使用的是Mysql),為了演示方便,我這裡簡單的建立一個spring資料庫,然後資料庫有一個user使用者表:
spring
CREATE TABLE `user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `email` varchar(255) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1; 複製程式碼

建立實體類
建立一個 實體類 和資料庫的表相對應(模型用來儲存要操作的資料)。 User.java:
package cn.biecheng.www.Entity; public class User { int id; String name; String email; String password; public User(String name, String email, String password){ this.email = email; this.name = name; this.password = password; } public void setId(int id) { this.id = id; } public int getId() { return id; } public String getEmail() { return email; } public String getName() { return name; } public String getPassword() { return password; } public void setEmail(String email) { this.email = email; } public void setName(String name) { this.name = name; } public void setPassword(String password) { this.password = password; } } 複製程式碼

資料訪問物件(DAO)模式
DAO(data access object),資料庫訪問物件,主要的功能就是用於驚險資料庫操作的。 UserDao.java:
UserDao介面
package cn.biecheng.www.Dao; import cn.biecheng.www.Entity.User; public interface UserDao { public void inSert(User user); } 複製程式碼

。
UserDao介面的實現
UserDaoImpl.java:
package cn.biecheng.www.Dao.impl; import cn.biecheng.www.Dao.UserDao; import cn.biecheng.www.Entity.User; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class UserDaoImpl implements UserDao { private Connection connection; //建構函式 向連線池獲得連線 UserDaoImpl(){ try{ Context initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/dataSource"); connection = ds.getConnection(); }catch (NamingException e){ System.out.println(e); }catch (SQLException e){ System.out.println(e); } } public void inSert(User user) { try{ PreparedStatement ps = connection.prepareStatement("insert into user(name,email,password) values(?,?,?)"); ps.setString(1,user.getName()); ps.setString(2,user.getEmail()); ps.setString(3,user.getPassword()); ps.executeUpdate(); }catch (SQLException e){ System.out.println(e); } } } 複製程式碼

注意這裡,通過JNDI查詢到資料來源。
Context initContext = new InitialContext(); DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/dataSource"); 複製程式碼
然後 connection = ds.getConnection();
在資料來源中獲取一個連線物件。
資料來源配置
配置context.xml
在webapp中新建一個 META-INF
資料夾,然後新建個 context.xml
來配置資料來源。 context.xml:
<?xml version="1.0" encoding="UTF-8"?> <Context> <Resource name="jdbc/dataSource" auth="Container" factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/spring" username="root" password="root" maxTotal="100" maxIdle="30" maxWaitMillis="1000" driverClassName="com.mysql.jdbc.Driver"> </Resource> </Context> 複製程式碼

配置web.xml
在web.xml中配置context.xml的引用關係。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <resource-ref> <res-ref-name>jdbc/dataSource</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> </web-app> 複製程式碼

測試
由於TomcatDBCP是內建在Tomcat容器的連線池,所以要使用這個連線池得執行Tomcat,接下來我們編寫在Tomcat容器中實現連線池操作資料庫。
測試類
- 新建一個測試類,來測試我們的連線池操作資料庫。需要注意的是,
servlet
的生命週期是由 servlet容器管理 (如Tomcat)的,而Spring的Bean是由 Srping容器 管理的,所以我們在servlet容器中是無法使用@Autowired
等Spring的註解的,那麼如何在Spring容器外面獲取到Spring容器的Bean例項呢?這就需要用到Spring為我們提供的WebApplicationContextUtils
工具類,該工具的作用是獲取到Spring容器的引用,進而獲得我們需要的Bean例項。 test.java:
package cn.biecheng.www.test; import cn.biecheng.www.Dao.impl.UserDaoImpl; import cn.biecheng.www.Entity.User; import org.apache.xbean.spring.context.ClassPathXmlApplicationContext; import org.springframework.context.ApplicationContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class test extends HttpServlet{ private UserDaoImpl userDaoImpl; public void doGet(HttpServletRequest args, HttpServletResponse args1) throws ServletException { //獲取spring的bean ApplicationContext applicationContext = new ClassPathXmlApplicationContext("context.xml"); this.userDaoImpl = (UserDaoImpl) applicationContext.getBean("userDaoImpl"); User user; user = new User("xue811", "xue8", "xue8"); userDaoImpl.inSert(user); } } 複製程式碼

- 我們在resources中新建一個context.xml進行配置Bean。 context.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <bean id="userDaoImpl" class="cn.biecheng.www.Dao.impl.UserDaoImpl"> </bean> </beans> 複製程式碼

Web配置
在 web.xml
配置檔案中新增servlet,來處理請求。我們將/index的請求讓 cn.biecheng.www.test.test
測試類進行處理。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>index</servlet-name> <servlet-class>cn.biecheng.www.test.test</servlet-class> </servlet> <servlet-mapping> <servlet-name>index</servlet-name> <url-pattern>/index</url-pattern> </servlet-mapping> <resource-ref> <res-ref-name>jdbc/dataSource</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> </web-app> 複製程式碼
執行測試
我們在IDEA執行後,在瀏覽器中輸入 http://localhost:8080/index
,即可在資料庫中發現數據已插入。

原文地址:ddnd.cn/2018/11/26/…