Spring4学习笔记-JDBC

引入的jar包与基于注解的方式引入的jar包相同


实体类

Employee.java   对应数据库中的employee表

public class Employee {
	private Integer id;
	private String last_name;
	private String email;
	private Department department;
	//...省略get、set方法
}	

Department.java   对应数据库中的department表

public class Department {
	private Integer id;
	private String name;
	//.....省略get、set方法
}

EmployeeDao.java

/**
 * 在实际开发中这么使用
 * @author umgsai
 */
@Repository
public class EmployeeDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;

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

DepartmentDao.java

/**
 * 不推荐使用JdbcDaoSupport,而推荐使用JdbcTemplate作为Dao类的成员变量
 * @author umgsai
 */
@Repository
public class DepartmentDao extends JdbcDaoSupport{

	//注入dataSource
	@Autowired
	public void setDataSource2(DataSource dataSource) {
		setDataSource(dataSource);
	}

	public Department get(Integer id) {
		Department department = null;
		String sql = "select id, name from department where id = ?";
		RowMapper<Department> rowMapper = new BeanPropertyRowMapper<>(Department.class);
		department = (Department) getJdbcTemplate().queryForObject(sql, rowMapper, id);
		return department;
	}
}

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 http://www.springframework.org/schema/context/spring-context-4.1.xsd">

	<context:component-scan base-package="com.spring.jdbc"></context:component-scan>
	<!-- 导入资源文件 -->
	<context:property-placeholder location="classpath:db.properties" />
	<!-- 配置C3P0数据源 -->
	<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="driverClass" value="${jdbc.driverClass}"></property>
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>

		<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
		<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
	</bean>

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

db.properties

jdbc.user=root
jdbc.password=123456
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///test

jdbc.initialPoolSize=5
jdbc.maxPoolSize=10

JDBCTest.java

public class JDBCTest {

	private ApplicationContext applicationContext = null;
	private JdbcTemplate jdbcTemplate;
	private EmployeeDao employeeDao;
	private DepartmentDao departmentDao;
	{
		applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
		employeeDao = applicationContext.getBean(EmployeeDao.class);
		departmentDao = applicationContext.getBean(DepartmentDao.class);
	}

	@Test
	public void testDepartmentDao() {
		System.out.println(departmentDao.get(2));
	}

	@Test
	public void testEmployeeDao() {
		System.out.println(employeeDao.get(9));
	}

	/**
	 * 获取单个列的值或做统计查询
	 */
	@Test
	public void testQueryForObject2() {
		String sql = "select count(id) from employee";
		long count = jdbcTemplate.queryForObject(sql, Long.class);
		System.out.println(count);
	}

	/**
	 * 查询实体集合
	 */
	@Test
	public void testQueryForList() {
		String sql = "select id, last_name, email, department_id as \"department.id\" from employee where id >0";
		RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
		List<Employee>employees = jdbcTemplate.query(sql, rowMapper);
		System.out.println(employees);
	}

	/**
	 * 从数据库获取一条记录,实际得到对应的一个对象。
	 * 不是ORM框架,不支持级联属性。
	 */
	@Test
	public void testQueryForObject() {
		String sql = "select id, last_name, email, department_id as \"department.id\" from employee where id = ?";
		RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
		Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, 9);
		System.out.println(employee);
	}

	/**
	 * 执行批量操作(update、insert、delete)
	 */
	@Test
	public void testBatch() {
		String  sql = "insert into employee (last_name, email,department_id) values (?, ?, ?)";
		List<Object[]>batchArgs = new ArrayList<Object[]>();
		batchArgs.add(new Object[]{"dd", "[email protected]", 2});
		batchArgs.add(new Object[]{"ff", "[email protected]", 2});
		batchArgs.add(new Object[]{"rr", "[email protected]", 3});
		batchArgs.add(new Object[]{"tt", "[email protected]", 4});
		batchArgs.add(new Object[]{"yy", "[email protected]", 1});
		batchArgs.add(new Object[]{"uu", "[email protected]", 1});
		jdbcTemplate.batchUpdate(sql, batchArgs);
	}

	@Test
	public void testUpdate() {
		String sql = "update employee set email = ? where id = ?";
		jdbcTemplate.update(sql, "[email protected]", 1);
	}

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

}





时间: 2024-12-29 15:15:41

Spring4学习笔记-JDBC的相关文章

JAVA学习笔记 -- JDBC及其应用

一.准备工作 1.开启SQL Server服务和启用TCP/IP  并且确认TCP端口 2.Eclipse下给项目导入sqljdbc4.jar包 将下载好的 sqljdbc_4.0.2206.100_chs.exe运行解压.然后在 .\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\chs\auth 路径下选择合适版本的sqljdbc_auth.dll, 将其放在 C:\Windows\System32下. 给项目导入包:右键你的项目选择

Java学习笔记--JDBC数据库的使用

参考  hu_shengyang的专栏 : http://blog.csdn.net/hu_shengyang/article/details/6290029 JDBC API中提供的常用数据库编程的类和接口如下 1.Driver 接口:代表驱动程序 2.DriverManager 类:驱动程序管理员 3.Connection 接口:代表数据库连接 4.Statement .PreparedStatement.CallableStatement 接口:代表数据库操作对象 5.ResultSet

Spring4学习笔记2-配置集合属性

1 可使用<list> <map> <set>等来配置集合属性 2 List <!-- 配置List属性 --> <bean id="person3" class="com.kejian.spring.bean.collectionbean.PersonForList"> <property name="name" value="Peter"></p

【转】jmeter学习笔记——JDBC测试计划-连接Mysql

我的环境:MySQL:mysql-essential-5.1.51-win32 jdbc驱动:我已经上传到csdn上一个:http://download.csdn.net/source/3451945 JMeter:jmeter-2.4  任意版本都行. 1.首先我们要有一个可以做测试的数据库,当然,里面要有数据,不然怎么测呢? 来看一下我的数据: 2.打开JMeter,点击测试计划,然后点击“浏览...”按钮,将你的JDBC驱动添加进来. 3.添加一个线程组 右键点击“线程组”,在下面添加一个

Spring4学习笔记-SpringJDBC基本操作(补充)

湘潭项目使用Spring+CXF编写服务器端,JDBC操作全部由Spring完成,下面记录其中一个典型的实例. public class Userinfo_lvDaoImpl implements Userinfo_lvDao {         //通过注解注入获得jdbcTemplate对象 @Autowired private JdbcTemplate jdbcTemplate; /**  * 根据name和password来查询用户.返回查询到的Userinfo_lv对象  */ @Ov

Spring4学习笔记-AOP(基于配置文件的方式)

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://shamrock.blog.51cto.com/2079212/1557743 引入的jar包与基于注解的方式引入的jar包相同 ArithmeticCalculator接口 1 2 3 4 5 6 7 8 9 10 11 package com.spring.aop.impl.xml; public interface ArithmeticCalculator {     pu

Spring4学习笔记-通过注解配置bean

通过注解配置Bean TestObject.java package com.spring.beans.annotation; import org.springframework.stereotype.Component;; @Component public class TestObject { } UserController.java package com.spring.beans.annotation.controller; import org.springframework.st

Spring4学习笔记-Spring4整合Struts2

Person.java public class Person { private String username; public void setUsername(String username) { this.username = username; } } PersonService.java public class PersonService { public void save() { System.out.println("PersonService save...");

Spring4学习笔记 - Bean的生命周期

1 Spring IOC 容器对 Bean 的生命周期进行管理的过程: 1)通过构造器或工厂方法创建 Bean 实例 2)为 Bean 的属性设置值和对其他 Bean 的引用 3)调用 Bean 的初始化方法 init-method 4)Bean 可以使用了 5)当容器关闭时, 调用 Bean 的销毁方法 destroy-method <!-- 设置init和destoy方法 --> <bean id="car" class="com.kejian.spri