1.使用jdbctemplate连接数据库
package com.feng.jdbctemplate;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class JdbcTemplateTest {
@Test
public void test() {
//目标:使用jdbctemplate执行一段sql
//1.构建数据源
//spring内置了一个数据源
DriverManagerDataSource dataSource=new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///fengspring");
dataSource.setUsername("root");
dataSource.setPassword("12345678");
//2.创建jdbctemplate实例
//等同于jdbcTemplate.setDateSourse(dateSourse)
JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
//3.执行sql,创建表test001
jdbcTemplate.execute("create table test001(id int ,name varchar(20))");
}
}
缺点:如要频繁连接数据库,时间开销会增大
2.使用连接池连接数据库
Spring内置数据源:将数据源和jdbcTemplate都交给Spring管理。
//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:aop="http://www.springframework.org/schema/aop"
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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 相当于DriverManagerDataSource dataSource=new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///fengspring");
dataSource.setUsername("root");
dataSource.setPassword("12345678"); -->
<!-- 配置内置的数据源bean -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///fengspring"></property>
<property name="username" value="root"></property>
<property name="password" value="12345678"></property>
</bean>
<!-- jdbctemplate对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class JdbcTemplateTest {
//注入要测试bean
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void test1() {
jdbcTemplate.execute("create table test002(id int ,name varchar(20))");
}
}
数据源:DriverManagerDataSource是spring内置的连接池,不建议生产环境使用,可以在测试环境使用
Apache DBCP连接池
//applicationContext.xml
<!-- 配置apache的dbcp连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///fengspring"></property>
<property name="username" value="root"></property>
<property name="password" value="12345678"></property>
</bean>
<!-- jdbctemplate对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class JdbcTemplateTest {
//注入要测试bean
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void test2() {
jdbcTemplate.execute("create table test003(id int ,name varchar(20))");
}
}
C3P0连接池
//applicaContex.xml
<!-- C3P0连接池配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///fengspring"></property>
<property name="user" value="root"></property>
<property name="password" value="12345678"></property>
</bean>
<!-- jdbctemplate对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class JdbcTemplateTest {
//注入要测试bean
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void test3() {
jdbcTemplate.execute("create table test004(id int ,name varchar(20))");
}
}
\
外部属性文件的配置(灵活性强)
//创建一个file文件 db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///fengspring
jdbc.username=root
jdbc.password=12345678
//applicationContext.xml
<!-- 引入外部属性配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置内置的数据源bean,使用db.properties -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- jdbctemplate对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class JdbcTemplateTest {
//注入要测试bean
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void test4() {
jdbcTemplate.execute("create table test005(id int ,name varchar(20))");
}
}
3.基于Jdbctemplate实现DAO(CURD)
实现增加,删除,修改功能
//实体类
package com.feng.domain;
public class Book {
private Integer id;
private String name;
private double price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
//dao层
package com.feng.dao;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import com.feng.domain.Book;
@Repository
public class BookDao extends JdbcDaoSupport{
//保存一本书
public void save() {
String sql="insert into book values(null,?,?)";
//pst.setString(1,"浪潮之巅")
//pst.setDouble(2.50D)
Book book=new Book();
book.setName("浪潮之巅");
book.setPrice(50D);
this.getJdbcTemplate().update(sql, book.getName(),book.getPrice());
}
}
//测试类
package com.feng;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.feng.dao.BookDao;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class DaoTest {
@Autowired
private BookDao bookDao;
@Test
public void testBookDao() {
bookDao.save();
}
}
//applicationContex.xml
<!-- 配置内置的数据源bean -->
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///fengspring"></property>
<property name="username" value="root"></property>
<property name="password" value="12345678"></property>
</bean> -->
<!-- 配置dao,注入jdbctemplate -->
<bean id="bookDao" class="com.feng.dao.BookDao">
<!-- 方案一:在BookDao中提供jdbcTemplate属性,通过set方法注入jdbctemplate -->
<!-- <property name="jdbcTemplate" ref="jdbcTemplate"></property> -->
<!-- 方案二:BookDao类继承JdbcDaoSupport,直接注入数据源,就拥有了jdbctemplate对象 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
修改:
//在BookDao类中加入update修改方法
//修改
public void update() {
String sql="update book set name=? where id=?";
this.getJdbcTemplate().update(sql, "java",1);
}
//在测试类增加测试方法
@Test
public void testBookDaoUpdate() {
bookDao.update();
}
删除:
//在BookDao类中加入删除方法
//删除
public void delete() {
String sql="delete from book where id=?";
this.getJdbcTemplate().update(sql,1);
}
//在测试类中增加测试方法
@Test
public void testBookDaoDelete() {
bookDao.delete();
}
4.简单返回值的查询
查询单个对象
//在BookDao增加
//根据id查询一个
public Book findById(int id) {
String sql="select * from book where id=?";
return this.getJdbcTemplate().queryForObject(sql, new BookRowMapper(),id);
}
//自定义的手动装配的类
class BookRowMapper implements RowMapper<Book>{
//参数1:自动将查询出来的结果集传进来
//返回是:封装好的数据对象
@Override
public Book mapRow(ResultSet rs, int rowNum) throws SQLException {
// TODO Auto-generated method stub
Book book=new Book();
//取当前指针的结果集
book.setId(rs.getInt(1));
book.setName(rs.getString(2));
book.setPrice(rs.getDouble(3));
return book;
}
}
//在测试类增加
@Test
public void testBookDaoQuery() {
Book book=bookDao.findById(1);
System.out.println(book);
}
查询所有记录
//在BookDao类增加
//返回所有数据
public List<Book> queryAll(){
String sql="select * from book";
return this.getJdbcTemplate().query(sql, new BookRowMapper());
}
//在测试类增加测试方法
@Test
public void testBookDaoQueryAll() {
List<Book> books=bookDao.queryAll();
for(Book book:books) {
System.out.println(book);
}
}
根据条件查询
//在BookDao类增加
//根据条件查询
public List<Book> queryAllByCondition(String name){
String sql="select * from book where name like ?";
return this.getJdbcTemplate().query(sql, new BookRowMapper(),"%"+name+"%");
}
//在测试类增加
@Test
public void queryAllByCondition() {
List<Book> books=bookDao.queryAllByCondition("Java");
for(Book book:books) {
System.out.println(book);
}
}