@[toc]java
前面咱們已經用Spring和傳統的Jdbc實現數據庫操做、Spring和JdbcTemplate實現數據庫操做。可是這些都是基於直連的數據源進行的,如今咱們將介紹基於鏈接池的數據源進行數據庫操做。前面幾個步驟都相同。mysql
首先建立咱們的數據庫(這裏我使用的是Mysql),爲了演示方便,我這裏簡單的建立一個spring數據庫,而後數據庫有一個user用戶表:web
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:spring
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(data access object),數據庫訪問對象,主要的功能就是用於驚險數據庫操做的。 UserDao.java:sql
package cn.biecheng.www.Dao;
import cn.biecheng.www.Entity.User;
public interface UserDao {
public void inSert(User user);
}
複製代碼
抽象了User的操做,即User能夠進行
插入操做(inSert)。
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();
在數據源中獲取一個鏈接對象。apache
在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中配置context.xml的引用關係。tomcat
<?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容器中實現鏈接池操做數據庫。bash
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);
}
}
複製代碼
<?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.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/…