Spring对持久层采取了很好的支持,这些支持策略主要有:
(1)Spring对持久层“不发明重复的轮子”,即没有重新实现新的持久层方案,对现有持久层方案做封装,更利于使用。
(2)采用DAO模式。
(3)提供了大量的模板类来简化编程(HibernateDaoSupport,JdbcTemplate等)
(4)重新设计了一套完善的异常体系结构:
①类型丰富,细化异常类型。
② 全都是运行时异常(RuntimeException)。
这里主要有两种方法
- JdbcTemplate
- JdbcDaoSupport(实际上使用的也是JdbcTemplate)
代码演示:
1、建库建表
2、编写实体类
public class Person {
private Long id;
private String name;
private Double money;
getter setter toString
3、导入必要jar包
JdbcTemplate简单的使用
手动在dao层加上一个模板类属性
Spring对持久层的操作:
增删改的时候都调用:update
查询单个时调用:queryForObject
查询全部调用:query
直接编写测试类:Demo1
public class Demo1 {
public static void main(String[] args) {
//使用Spring JDBCTemplate模板操作数据库
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/spring?characterEncoding=utf-8");
dataSource.setUsername("root");
dataSource.setPassword("666");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
//添加
/*String sql = "insert into person (name,money) values (?,?)";
int row = jdbcTemplate.update(sql,"李四",250);
if(row>0){
System.out.println("添加成功");
}*/
//修改
/*String sql1 = "update person set name=?,money=? where id=?";
int row1 = jdbcTemplate.update(sql1,"张麻子",3000,3);
if(row1>0){
System.out.println("修改成功");
}*/
//删除
/*String sql2 = "delete from person where id=?";
int row2 = jdbcTemplate.update(sql2, 4);
if(row2>0){
System.out.println("删除成功");
}*/
//查询一个
/*String selectSql = "select * from person where id=?";
Person person = jdbcTemplate.queryForObject(selectSql, new BeanPropertyRowMapper<>(Person.class), 3);
System.out.println(person);*/
//查询所有
String selectAll = "select * from person";
List<Person> people = jdbcTemplate.query(selectAll, new BeanPropertyRowMapper<>(Person.class));
System.out.println(people);
}
}
以上代码只是简单的演示了JdbcTemplate的使用,并不优雅,需要进一步优化代码—>
对代码进一步进行优化
- 创建对象交给Spring管理
- 数据库连接信息抽出
- 引入DruidDataSource数据源
- 使用Spring集成junit编写测试类
1、抽取db.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?characterEncoding=utf-8
jdbc.username=root
jdbc.password=666
2、编写PersonDao
public interface PersonDao {
/**
* 查询所有
* @return
*/
List<Person> findAll();
/**
* 根据id查询
* @param id
* @return
*/
Person findById(Long id);
/**
* 添加
*/
int addPerson(Person person);
/**
* 修改
*/
int updatePerson(Person person);
/**
* 删除
*/
int deleteById(Long id);
}
3、编写PersonDaoImpl
@Component
public class PersonDaoImpl implements PersonDao {
@Autowired//从容器中获取对象
private JdbcTemplate jdbcTemplate;
@Override
public List<Person> findAll() {
return jdbcTemplate.query("select * from person",new BeanPropertyRowMapper<>(Person.class));
}
@Override
public Person findById(Long id) {
return jdbcTemplate.queryForObject("select * from person where id =?",new BeanPropertyRowMapper<>(Person.class),id);
}
@Override
public int addPerson(Person person) {
return jdbcTemplate.update("insert into person (name,money) values (?,?)",person.getName(),person.getMoney());
}
@Override
public int updatePerson(Person person) {
return jdbcTemplate.update("update person set name=?,money=? where id=?",person.getName(),person.getMoney(),person.getId());
}
@Override
public int deleteById(Long id) {
return jdbcTemplate.update("delete from person where id=?",id);
}
}
4、编写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: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 https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 加载外部配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 包扫描-->
<context:component-scan base-package="com.codeyancy.cn"/>
<!-- 配置数据源信息
DriverManagerDataSource spring-jdbc 提供的这个数据源 是没有缓冲池的
使用外部数据源 使用Druid :DruidDataSource
-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置jdbcTemplate 交给spring管理-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
5、编写测试类
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class Demo2 {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void test(){
//添加
// String sql = "insert into person (name,money) values (?,?)";
// int row = jdbcTemplate.update(sql,"李ss",2050);
// if(row>0){
// System.out.println("添加成功");
// }
//查询一个
// String selectOne = "select * from person where id = ?";
// Person person = jdbcTemplate.queryForObject(selectOne, new BeanPropertyRowMapper<>(Person.class), 1);
// System.out.println(person);
//查询所有
String selectAll = "select * from person";
List<Person> people = jdbcTemplate.query(selectAll, new BeanPropertyRowMapper<>(Person.class));
System.out.println(people);
}
}
JdbcDaoSupport的使用
让dao的实现类继承daoSupport
不需要在配置文件中去注入模板类
获得模板类对象:getJdbcTemplate()
与上面的代码相比只需要修改两个文件即可
代码:
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: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 https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 加载外部配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="personDao" class="com.codeyancy.cn.dao.impl.PersonDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置数据源信息
DriverManagerDataSource spring-jdbc 提供的这个数据源 是没有缓冲池的
使用外部数据源 使用Druid :DruidDataSource
-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
PersonDaoImpl
public class PersonDaoImpl extends JdbcDaoSupport implements PersonDao {
@Override
public List<Person> findAll() {
return getJdbcTemplate().query("select * from person",new BeanPropertyRowMapper<>(Person.class));
}
@Override
public Person findById(Long id) {
return getJdbcTemplate().queryForObject("select * from person where id =?",new BeanPropertyRowMapper<>(Person.class),id);
}
@Override
public int addPerson(Person person) {
return getJdbcTemplate().update("insert into person (name,money) values (?,?)",person.getName(),person.getMoney());
}
@Override
public int updatePerson(Person person) {
return getJdbcTemplate().update("update person set name=?,money=? where id=?",person.getName(),person.getMoney(),person.getId());
}
@Override
public int deleteById(Long id) {
return getJdbcTemplate().update("delete from person where id=?",id);
}
}
使用之前测试类测试即可。