Spring09 第九 spring JDBCTemplate基本使用
1. Spring JdbcTemplate基本使用
1.1 JdbcTemplate
概述它是spring框架中提供的一个对象,是对原始繁琐的JdbcAPI对象的简单封装。spring框架为我们提供了很多的操作模板类。例如:操作关系型数据的JdbcTemplate和HibernateTemplate,操作nosql数据库的RedisTemplate,操作消息队列的JmsTemplate等等。
1.2 JdbcTemplate开发步骤
①导入spring-jdbc和spring-tx坐标②创建数据库表和实体③创建JdbcTemplate对象④执行数据库操作
【因为jdbcTemplate底层使用事务,所以要导入spring-tx事务坐标】
①导入坐标
<!--导入spring的jdbc坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--导入spring的tx坐标(事务)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
②创建accout表和Accout实体
③创建JdbcTemplate对象④执行数据库操作
测试代码:
public class JdbcTemplateTest{
@Test
public void test(){
//1、创建数据源对象
ComboPooledDataSourcedataSource= new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setPassword("root");
//2、创建JdbcTemplate对象
JdbcTemplatejdbcTemplate= new JdbcTemplate();
//3、设置数据源给JdbcTemplate
jdbcTemplate.setDataSource(dataSource);
//4、执行操作
jdbcTemplate.update("insert into account values(?,?)","tom",5000);
}
}
1.3 Spring产生JdbcTemplate对象
我们可以将JdbcTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部将数据源DataSource注入到JdbcTemplate模版对象中,
1.3.1 配置如下:
<!--数据源DataSource-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver">
</property>
<property name="jdbcUrl" value="jdbc:mysql:///test">
</property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!--JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
1.3.2从容器中获得JdbcTemplate进行添加操作
@Test
public void testSpringJdbcTemplate() throws PropertyVetoException{
ApplicationContextapplicationContext= new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplatejdbcTemplate= applicationContext.getBean(JdbcTemplate.class);
jdbcTemplate.update("insert into account values(?,?)","lucy",5000);}
修改操作(使用Spring集成Junit测试)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest{
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
//测试修改操作
public void testUpdate(){
jdbcTemplate.update("update account set money=? where name=?",1000,"tom");}}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了