返回介绍

01-03、JdbcTemplate

发布于 2025-03-09 23:21:23 字数 10766 浏览 0 评论 0 收藏 0

JdbcTemplate 是 Spring MVC 内置的对 JDBC 的一个封装。

数据库准备

MySQL 5.6。

--创建数据库
CREATE DATABASE IF NOT EXISTS `test` DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
USE `test`;
--创建 table
CREATE TABLE IF NOT EXISTS user
(
  `id` int AUTO_INCREMENT,
  `name` varchar(255),
  `email` varchar(255),
  `age` varchar(255),
  `passwd` varchar(255),
  PRIMARY KEY (`id`),
  UNIQUE KEY (`name`),
  UNIQUE KEY (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
---插入若干数据
INSERT INTO user (`name`, `email`, `age`, `passwd`)
VALUES ('user01', 'user01@163.com', 20, password('123'));

INSERT INTO user (`name`, `email`, `age`, `passwd`)
VALUES ('user02', 'user02@163.com', 20, password('456'));

INSERT INTO user (`name`, `email`, `age`, `passwd`)
VALUES ('用户 03', 'user03@163.com', 20, password('456'));

示例 1

继续使用的上一节 01-02、使用 Spring MVC 构建 Hello World 中创建的项目。

项目结构如下:

图中红线下的文件是新增或者修改的文件。

MySQL 的 JDBC 封装 mysql-connector-java-**.jar 别忘了放到 Libraries 里。

源码

SelectController.java 源码:

package me.letiantian.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.jdbc.core.JdbcTemplate;

import me.letiantian.service.UserService;

public class SelectController implements  Controller{

  @Autowired
  private UserService userDao;

  @Autowired
  private JdbcTemplate jdbcTemplate;

  @Override
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("text/html;charset=UTF-8");
    ModelAndView mv = new ModelAndView();

    List users = jdbcTemplate.queryForList("SELECT * FROM user");
    mv.addObject("users", users);

    Map user1 = userDao.getUserById(1);
    mv.addObject("user1", user1);

    Map user2 = jdbcTemplate.queryForMap("SELECT * FROM user WHERE id=2");
    mv.addObject("user2", user2);

    mv.addObject("message", "无错误信息");
    mv.setViewName("select");
    return mv;
  }

}

UserService.java 源码:

package me.letiantian.service;

import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class UserService {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  public Map getUserById(int id) {

    Map user = jdbcTemplate.queryForMap("SELECT * FROM user WHERE id=?", new Object[] {id});
    return user;

  }

}

select.jsp 源码:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
  </head>
  <body>
    <h1>Hello World!</h1>
  <c:if test="${not empty users}">
      <ul>
        <c:forEach var="user" items="${users}">
          <li>
            <c:forEach var="entry" items="${user}">  
              <c:out value="${entry.key}" /> :   
              <c:out value="${entry.value}" />  
            </c:forEach>  
          </li>
        </c:forEach>
      </ul>
  </c:if>

    <hr/>

    <c:if test="${not empty user1}">
      <ul>
        <c:forEach var="entry" items="${user1}">  
          <li>
            <c:out value="${entry.key}" />  
            <c:out value="${entry.value}" />   
          </li>
        </c:forEach>  
      </ul>
  </c:if>

    <hr/>

    <c:if test="${not empty user2}">
      <ul>
        <c:forEach var="entry" items="${user2}">  
          <li>
            <c:out value="${entry.key}" />  
            <c:out value="${entry.value}" />   
          </li>
        </c:forEach>  
      </ul>
  </c:if>
    <h2>${message}</h2>
  </body>
</html>

dispatcher-servlet.xml 源码:

<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:p="http://www.springframework.org/schema/p"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

  <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

  <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

  <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
      <props>
        <prop key="index">indexController</prop>
        <prop key="hello">helloController</prop>
        <prop key="select">selectController</prop>
      </props>
    </property>
  </bean>

  <bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />

  <bean name="indexController"
      class="org.springframework.web.servlet.mvc.ParameterizableViewController"
      p:viewName="index" />

  <bean name="helloController"
      class="me.letiantian.controller.HelloController" />

  <bean name="selectController"
      class="me.letiantian.controller.SelectController" />

  <mvc:resources mapping="/static/**" location="/static/"/>  

</beans>

该文件中新增加了 selectController ,以及 <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 以使得 @Autowired 能够工作。

applicationContext.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:p="http://www.springframework.org/schema/p"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

  <context:component-scan base-package="me.letiantian.controller" />
  <context:component-scan base-package="me.letiantian.service" />

  <bean id="dataSource"
      class="org.springframework.jdbc.datasource.DriverManagerDataSource"
      p:driverClassName="com.mysql.jdbc.Driver"
      p:url="jdbc:mysql://localhost:3306/test"
      p:username="root"
      p:password="123456" />

  <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
  </bean>

</beans>

dataSource 设置程 MySQL,并注入到 jdbcTemplate

运行项目,浏览器访问:

资料

JdbcTemplate 中的有多种查询方法,可以参考:
JdbcTemplate 查询
Spring JdbcTemplate 方法详解

上面的 JSP 中用到了 JSTL,以下几篇文件可以看一下:
在 JSTL EL 中处理 java.util.Map,及嵌套 List 的情况
JSP 标准标签库(JSTL)

JdbcTemplate 也可以使用事务,有声明式和编程式两种方法:
Spring Declarative Transactions
Spring Programmatic Transactions
Spring Programmatic Transaction Management
Spring JdbcTemplate 与 事务管理
Transactions with JdbcTemplate

如何使用连接池?
JDBC Database connection pool in Spring FrameWork - How to SetUp Example
Setup Connection Pooling in Spring MVC

其他:
Spring MVC with JdbcTemplate Example
Spring MVC and List Example

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文