您的位置:首页 > 编程语言 > Java开发

Spring_23-24使用 JdbcTemplate和JdbcDaoSupport和NamedParameterJdbcTemplate

2017-02-13 21:38 691 查看
作为了解即可,主要还是关注在sql语句的使用和orm的框架habernate,mybaties

重点:

1,学习如何引用外部资源文件和配置数据源

<!-- 配置扫描的包 -->
<context:component-scan base-package="com.hgh.spring.jdbc"></context:component-scan>
<!-- 导入资源文件 -->
<context:property-placeholder location="classpath:db.property"/>

<!-- 配置数据源 -->
<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.driver}"></property>
</bean>


2,学习使用org.springframework.jdbc.core.JdbcTemplate的一些基本用法,实现增删改查,重点在批量:jdbcTemplate.batchUpdate(sql, list);和BeanPropertyRowMapper实现数据库到java类的映射

@Test
public void testQueryForOne(){
String sql = "select id , last_name,email from employee where id=?";
RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class);
Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, 1);
System.out.println(employee);

}


重点3:使用NamedParameterJdbcTemplate实现别名.

/**
* 可以为参数起名字.
* 1. 好处: 若有多个参数, 则不用再去对应位置, 直接对应参数名, 便于维护
* 2. 缺点: 较为麻烦.
*/
@Test
public void testNamedParameterJdbcTemplate(){
String sql = "insert into employee(email,last_name) values(:email,:last_name) ";
Map<String, Object> map = new HashMap<String, Object>();
map.put("email", "222@qq.com");
map.put("last_name", "hgh41213");
namedParameterJdbcTemplate.update(sql, map);
}


aplicationcontext.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"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置扫描的包 --> <context:component-scan base-package="com.hgh.spring.jdbc"></context:component-scan> <!-- 导入资源文件 --> <context:property-placeholder location="classpath:db.property"/> <!-- 配置数据源 --> <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.driver}"></property> </bean>

<!-- 配置spring的jdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>

<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
</beans>


JDBCTest

package com.hgh.spring.jdbc;

import static org.junit.Assert.*;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

public class JDBCTest {

private ApplicationContext ac = null;
private JdbcTemplate jdbcTemplate=null;
private EmployeeDao employeeDao;
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

{
ac = new ClassPathXmlApplicationContext("aplicationcontext.xml");
jdbcTemplate = (JdbcTemplate) ac.getBean("jdbcTemplate");
employeeDao = (EmployeeDao) ac.getBean("employeeDao");
namedParameterJdbcTemplate = (NamedParameterJdbcTemplate) ac.getBean("namedParameterJdbcTemplate");
}
/**
* 可以为参数起名字.
* 1. 好处: 若有多个参数, 则不用再去对应位置, 直接对应参数名, 便于维护
* 2. 缺点: 较为麻烦.
*/
@Test
public void testNamedParameterJdbcTemplate(){
String sql = "insert into employee(email,last_name) values(:email,:last_name) ";
Map<String, Object> map = new HashMap<String, Object>();
map.put("email", "222@qq.com");
map.put("last_name", "hgh41213");
namedParameterJdbcTemplate.update(sql, map);
}

/**
* 测试DAO的调用方法
*/
@Test
public void testGetEmployee(){
System.out.println(employeeDao.getEmployee(2));
}

@Test
public void testForOne(){
String sql = "select count(id) from employee";
Long count = jdbcTemplate.queryForObject(sql, Long.class);
System.out.println(count);
}

/**
* 查到实体类的集合
* 注意调用的不是 queryForList 方法
*/
@Test
public void testQueryForList(){
String sql = "SELECT id, last_name, email FROM employee WHERE id < ?";
RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
List<Employee> employees = jdbcTemplate.query(sql, rowMapper,5);

System.out.println(employees);
}

/**
* 从数据库中获取一条记录, 实际得到对应的一个对象
* 注意不是调用 queryForObject(String sql, Class<Employee> requiredType, Object... args) 方法!
* 而需要调用 queryForObject(String sql, RowMapper<Employee> rowMapper, Object... args)
* 1. 其中的 RowMapper 指定如何去映射结果集的行, 常用的实现类为 BeanPropertyRowMapper
* 2. 使用 SQL 中列的别名完成列名和类的属性名的映射. 例如 last_name lastName
* 3. 不支持级联属性. JdbcTemplate 到底是一个 JDBC 的小工具, 而不是 ORM 框架
*/
@Test
public void testQueryForOne(){
String sql = "select id , last_name,email from employee where id=?";
RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class);
Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, 1);
System.out.println(employee);

}
/**
* 执行批量更新: 批量的 INSERT, UPDATE, DELETE
* 最后一个参数是 Object[] 的 List 类型: 因为修改一条记录需要一个 Object 的数组, 那么多条不就需要多个 Object 的数组吗
*/
@Test
public void testBathUpdate(){
List<Object[]> list = new ArrayList<Object[]>();
String sql = "insert into employee(email,last_name) values(?,?)";
list.add(new Object[]{"11","11@qq.com"});
list.add(new Object[]{"12","12@qq.com"});
list.add(new Object[]{"13","13@qq.com"});
list.add(new Object[]{"14","14@qq.com"});
jdbcTemplate.batchUpdate(sql, list);
}

/**
* 执行 INSERT, UPDATE, DELETE
*/
@Test
public void testInsert(){
String sql2 = "insert into employee(email,last_name) values('hgh33','1122@qq.com')";
String sql = "update employee set email=? where id=?";
jdbcTemplate.update(sql,"qq.qq.com",1);
jdbcTemplate.update(sql2);
}

@Test
public void test() {
DataSource dataSource = ac.getBean(DataSource.class);
try {
System.out.println(dataSource.getConnection());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}


EmployeeDao

package com.hgh.spring.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDao {

@Autowired
private JdbcTemplate jdbcTemplate;

public Employee getEmployee(Integer id){
String sql ="select id,email,last_name from employee where id=?";
RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class);
Employee employee = jdbcTemplate.queryForObject(sql, rowMapper,id);

return employee;
}
}


Employee

package com.hgh.spring.jdbc;

public class Employee {

private int id;
private String email;
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Employee() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Employee [id=" + id + ", email=" + email + ", lastName="
+ lastName + "]";
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring