概述:
spring对很多技术复杂繁琐的代码进行封装,JDBCTemplate就是其中一种
如:操作关系型数据的JdbcTemplate和HibernateTemplate,操作nosql数据库的RedisTemplate,操作消息队列的JmsTemplate等等。
步骤:
- 导入spring-jdbc和spring-tx【】坐标
<!--JDBCTemplte-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
- 创建数据库表和实体
- 创建JdbcTemplate对象
@Test
public void test1() throws SQLException {
//创建数据源
DruidDataSource dataSource=new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("JDBC:mysql://localhost:3306/springtest");
dataSource.setUsername("root");
dataSource.setPassword("123456");
//创建JDBCTemplate对象
JdbcTemplate template=new JdbcTemplate(dataSource);
String sql="insert into account(name,money) values(?,?)";
int count = template.update(sql, "zhangsan", 1200);
System.out.println(count);
}
- 执行数据库操作
spring产生模板对象代码实现(抽取jdbc.properties)
<?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
">
<!--寻找jdbc.properties配置文件-->
<context:property-placeholder location="classpath:Jdbc.properties" />
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
Jdbc基本使用:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplate_CRUD {
@Autowired
private JdbcTemplate template;
@Test
public void testUpdate(){
int row = template.update("update account set money=? where name=?", 2000, "王五");
}
@Test
public void testDelete(){
int row = template.update("delete from account where name=?", "??");
}
/**
* 查询多个对象
*/
@Test
public void testQuery(){
List<Account> AccountList = template.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
System.out.println(AccountList);
}
/**
* 查询多个多项
*/
@Test
public void testQueryOne(){
Account account = template.queryForObject("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), "王五");
System.out.println(account);
}
/**
* 聚合函数查询
*/
@Test
public void testQueryCount(){
long count = template.queryForObject("select count(*) from account",long.class);
System.out.println(count);
}
}
网友评论