1. 程式人生 > 其它 >SpringMVC JDBCtemplate的基本使用

SpringMVC JDBCtemplate的基本使用

JdbcTemplate概述

它是spring框架中提供的一個物件,是對原始繁瑣的JdbcAPI物件的簡單封裝。spring框架為我們提供了很多的操作模板類。例如:操作關係型資料的JdbcTemplate和HibernateTemplate,操作nosql資料庫的RedisTemplate,操作訊息佇列的JmsTemplate等等。

JdbcTemplate開發步驟

1)匯入spring-jdbc和spring-tx座標
2)建立資料庫表和實體
3)建立JdbcTemplate物件
4)執行資料庫操作

匯入座標

   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.3.13</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.3.13</version>
    </dependency>

註冊資料庫表和實體類


在MySQL資料庫建立 accout資料庫 建立detail 資料表

spring-mvc.xml中

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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.xsd
          http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
    <context:property-placeholder location="classpath:jdbc.properties"/> //載入配置檔案
 </bean>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>