【Java】Spring和Tomcat自带的连接池实现数据库操作

栏目: Java · 发布时间: 5年前

内容简介:前面我们已经用首先创建我们的数据库(这里我使用的是Mysql),为了演示方便,我这里简单的创建一个spring数据库,然后数据库有一个user用户表:创建一个

前面我们已经用 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;
复制代码
【Java】Spring和Tomcat自带的连接池实现数据库操作

创建实体类

创建一个 实体类 和数据库的表相对应(模型用来储存要操作的数据)。 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;
    }
}

复制代码
【Java】Spring和Tomcat自带的连接池实现数据库操作

数据访问对象(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);
}
复制代码
【Java】Spring和Tomcat自带的连接池实现数据库操作
抽象 了User的操作,即User可以进行 插入操作(inSert)

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);
        }
    }
}
复制代码
【Java】Spring和Tomcat自带的连接池实现数据库操作

注意这里,通过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>
复制代码
【Java】Spring和Tomcat自带的连接池实现数据库操作

配置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>

复制代码
【Java】Spring和Tomcat自带的连接池实现数据库操作

测试

由于TomcatDBCP是内置在Tomcat容器的连接池,所以要使用这个连接池得运行Tomcat,接下来我们编写在Tomcat容器中实现连接池操作数据库。

测试类

  1. 新建一个测试类,来测试我们的连接池操作数据库。需要注意的是, 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);
    }
}
复制代码
【Java】Spring和Tomcat自带的连接池实现数据库操作
  1. 我们在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>
复制代码
【Java】Spring和Tomcat自带的连接池实现数据库操作

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 ,即可在数据库中发现数据已插入。

【Java】Spring和Tomcat自带的连接池实现数据库操作

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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

《裂变:秒懂人工智能的基础课》

《裂变:秒懂人工智能的基础课》

王天一 / 电子工业出版社·博文视点 / 2018-6-13 / 59.00元

人工智能是指通过普通计算机程序实现的人类智能技术,这一学科不仅具有非凡的科学意义,对人类自身生存方式的影响也在不断加深。本书作为人工智能领域的入门读物,内容围绕人工智能的核心框架展开,具体包括数学基础知识、机器学习算法、人工神经网络原理、深度学习方法与实例、深度学习之外的人工智能和实践应用场景等模块。本书力图为人工智能初学者提供关于这一领域的全面认识,也为进一步的深入研究建立坚实的基础。一起来看看 《《裂变:秒懂人工智能的基础课》》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具