码迷,mamicode.com
首页 > 数据库 > 详细

Spring(十三)Spring整合JDBC

时间:2015-07-26 22:38:59      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:

做开发不连接数据库怎么行!Spring整合JDBC过程中,数据源可以直接都在beans.xml里配置,也可以把数据单独放在一个properties文件里,方便维护。

首先放入各种jar包,连接MySQL当然要放数据驱动文件。

jar包什么的对照项目截图,切面aspect和cglib在这个工程没用到,jar包可以不添加进来

技术分享

beans.xml,在头文件加上tx事务相关的引用,其他要注意的在文件的注释里基本都点到了

<?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"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- 加上classpath明确指定配置文件在类路径底下 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<!-- 可以把这些配置信息放在同一个配置文件里面 -->
		<!-- 
		<property name="driverClassName" value="org.gjt.mm.mysql.Driver" /> 
		<property name="url" value="jdbc:mysql://localhost:3306/spring_2015?useUnicode=true&characterEncoding=UTF-8"/> 
		<property name="username" value="root" /> 
		<property name="password" value="686175"/> 
		<property name="initialSize" value="1" /> 
		<property name="maxActive" value="500"/> 
		<property name="maxIdle" value="2"/> 
		<property name="minIdle" value="1"/> 
		-->
		<property name="driverClassName" value="${driverClassName}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
		<property name="initialSize" value="${initialSize}" />
		<property name="maxActive" value="${maxActive}" />
		<property name="maxIdle" value="${maxIdle}" />
		<property name="minIdle" value="${minIdle}" />
	</bean>

	<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 采用@Transaction注解方式使用事务 -->

	<tx:annotation-driven transaction-manager="txManager" />

	<!-- 将PersonServiceImpl交给Spring管理 -->
	<bean id="personService" class="test.spring.service.impl.PersonServiceImpl">
		<!-- 通过xml的方式对数据源进行注入 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
</beans>

jdbc.properties

driverClassName=org.gjt.mm.mysql.Driver
url=jdbc\:mysql\://localhost\:3306/spring_2015?useUnicode\=true&characterEncoding\=UTF-8
username=root
password=686175
initialSize=1
maxActive=500
maxIdle=2
minIdle=1
技术分享

测试用到的数据库spring_2015,表person

技术分享

实体类

package test.spring.entity;

public class Person {

	private Integer id;
	private String name;

	public Person() {

	}

	public Person(String name) {
		super();
		this.name = name;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "[Person:id = " + id + ",name = " + name + "]";
	}

}
业务实现类,注意在类前面加上@Transactional注解,这样能保证一个业务操作在一个单独的事务里面执行
package test.spring.service.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import test.spring.entity.Person;
import test.spring.service.PersonService;

@Transactional
public class PersonServiceImpl implements PersonService {

	// private DataSource dataSource;
	private JdbcTemplate jTemplate;

	public void setDataSource(DataSource dataSource) {
		// this.dataSource = dataSource;
		this.jTemplate = new JdbcTemplate(dataSource);
	}

	@Override
	public void save(Person person) {
		// TODO Auto-generated method stub
		jTemplate.update("insert into person(name) values(?)",
				new Object[] { person.getName() },
				new int[] { java.sql.Types.VARCHAR });
	}

	@Override
	public void update(Person person) {
		// TODO Auto-generated method stub
		jTemplate.update("update person set name=? where id=?", new Object[] {
				person.getName(), person.getId() }, new int[] {
				java.sql.Types.VARCHAR, java.sql.Types.INTEGER });
	}

	@Override
	public Person getPerson(Integer personId) {
		// TODO Auto-generated method stub
		Person person = (Person) jTemplate.queryForObject(
				"select * from person where id=?", new Object[] { personId },
				new int[] { java.sql.Types.INTEGER }, new PersonRowMapper());
		return person;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Person> getPersons() {
		// TODO Auto-generated method stub
		List<Person> persons = jTemplate.query("select * from person",
				new PersonRowMapper());
		return persons;
	}

	@Override
	public void delete(Integer personId) {
		// TODO Auto-generated method stub
		jTemplate
				.update("delete from person where id=?",
						new Object[] { personId },
						new int[] { java.sql.Types.INTEGER });
	}

}

各个方法的测试

package test.spring.junit;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import test.spring.entity.Person;
import test.spring.service.PersonService;

public class SpringAndJDBCTest {

	private static PersonService pService;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		AbstractApplicationContext aContext = new ClassPathXmlApplicationContext(
				"beans.xml");
		pService = (PersonService) aContext.getBean("personService");
	}

	@Test
	public void testSave() {
		pService.save(new Person("LinDL"));
	}

	@Test
	public void testGetPerson() {
		Person person = pService.getPerson(1);
		System.out.println(person.getName());
	}

	@Test
	public void testGetPersons() {
		List<Person> list = pService.getPersons();
		for (Person person : list) {
			System.out.println(person);
		}
	}

	@Test
	public void testUpdate() {
		Person person = pService.getPerson(1);
		person.setName("张大春");
		pService.update(person);
	}

	@Test
	public void testDelete() {
		pService.delete(1);
	}

}


版权声明:本文为博主原创文章,未经博主允许不得转载。如需转载,请注明出处:http://blog.csdn.net/lindonglian

Spring(十三)Spring整合JDBC

标签:

原文地址:http://blog.csdn.net/lindonglian/article/details/47072417

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!