1. 程式人生 > >spring JDBC模板

spring JDBC模板

pat 相關 xsd localhost version 數據庫驅動 money app conf

Spring的JDBC的模板

  • Spring是EE開發的一站式的框架,有EE開發的每層的解決方案。
  • Spring對持久層也提供了解決方案:ORM模塊和JDBC的模板。
  • Spring提供了很多的模板用於簡化開發
    • JDBC:org.springframework.jdbc.core.jdbc.jdbcTemplate
    • Hibernate:orm.springframework.orm.hibernamte.HibernateTemplate

JDBC模板使用的入門

引入jar包

  • spring開發基本jar包
  • 數據庫驅動
  • Spring的JDBC模板的jar包

技術分享圖片

創建數據庫和表

create table account(
    id int primary key auto_increment,
    name varchar(20),
    money double
);

使用JDBC的模板

@Test
public void test() {
    // 1. 創建連接池(數據庫相關信息)
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    // "jdbc:mysql:///spring" 相當於 "dbc:mysql://localhost:3306/spring"
    dataSource.setUrl("jdbc:mysql://localhost:3307/spring");
    dataSource.setUsername("root");
    dataSource.setPassword("123456");
    // 2. 創建JDBC模板
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.update("insert into account values (null,?,?)", "IT666", 1000d);
}

將連接池和模板交給Spring管理

配置文件配置Bean

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3307/spring"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

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

技術分享圖片

使用jdbcTemplate註解插入數據

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJdbcTest2 {

    @Resource(name = "jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    @Test
    public void test() {
        jdbcTemplate.update("insert into account values (null,?,?)", "IT888", 1000d);
    }
}

spring JDBC模板