Spring-JdbcTemplate-春天的故事5

来源:互联网 发布:牛排的做法 知乎 编辑:程序博客网 时间:2024/05/06 02:30

spring JdbcTemplate使用


  • 1、引包

除了引入spring配置的相关包,还需引入数据配置相关的包。

<dependency>          <groupId>c3p0</groupId>          <artifactId>c3p0</artifactId>          <version>0.9.1.2</version>      </dependency>      <dependency>          <groupId>mysql</groupId>          <artifactId>mysql-connector-java</artifactId>          <version>5.1.18</version>      </dependency>
  • 2、spring配置文件

数据库配置文件 db.properties

jdbc.user=rootjdbc.password=123456jdbc.driverClass=com.mysql.jdbc.Driver#本地创建的数据库名hibernate(任意名)jdbc.url=jdbc:mysql:///hibernatejdbc.initPoolSize=5jdbc.maxPoolSize=10

spring配置文件 applicationContext3.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.xsd">    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>    <!--配置c3p0数据源-->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="user" value="${jdbc.user}"></property>        <property name="password" value="${jdbc.password}"></property>        <property name="jdbcUrl" value="${jdbc.url}"></property>        <property name="driverClass" value="${jdbc.driverClass}"></property>        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>    </bean>    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">        <property name="dataSource" ref="dataSource"></property>    </bean>    </beans>
  • 3、简单使用
public class Main {    private JdbcTemplate jdbcTemplate;    {        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext3.xml");        jdbcTemplate= (JdbcTemplate) applicationContext.getBean("jdbcTemplate");    }    @Test    public void testUpdate(){        String sql="update news set author=? where id=?";        jdbcTemplate.update(sql,"jack",1);    }    /**     * RowMapper指定如何去映射完成结果集的行,常用实现类BeanPropertyRowMapper     *      */    @Test    public void  testQueryForObject(){        String sql="select * from news where id=?";        RowMapper<News> rowMapper=new BeanPropertyRowMapper<News>(News.class);        News news=jdbcTemplate.queryForObject(sql,rowMapper,1);        System.out.println(news);    }}
0 0