Spring+JDBC组合开发及环境搭建
知识点;
【
<1、使用Spring+JDBC集成步骤如下:
配置数据源,如:
<bean id="dataSource" destroy-method="close">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
.....略
</bean>
配置事务。配置事务时,需要在xml配置文件中引入用于声明事务的tx命名空间(见下页),事务的配置方式有两种:注解方式和基于XML配置方式。
在spring配置文件中引入用于声明事务的tx命名空间:
<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: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/tx http://www.springframework.org/schema/tx/spring-tx-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/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
</beans>
<2、配置数据源:
<bean id="dataSource" destroy-method="close">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="1"/>
<!-- 连接池的最大值 -->
<property name="maxActive" value="500"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="2"/>
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="1"/>
</bean>
使用<context:property-placeholder location=“jdbc.properties”/>属性占位符
<3、使用属性占位符方式配置数据源:
<context:property-placeholder location=“jdbc.properties”/>
<bean id="dataSource" destroy-method="close">
<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}"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}"/>
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="${minIdle}"/>
</bean>
<4、采用注解方式配置事务:
采用注解方式
<bean id="txManager" ref="dataSource"/>
</bean>
<!– 采用@Transactional注解方式使用事务 -->
<tx:annotation-driven transaction-manager="txManager"/>
@Service @Transactional
public class PersonServiceBean implements PersonService {
}
<5、采用基于XML方式配置事务:
<bean id="txManager" ref="dataSource"/>
</bean>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* cn.itcast.service..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<6、使用JdbcTemplate进行insert/update/delete操作:
@Service @Transactional
public class PersonServiceBean implements PersonService {
private JdbcTemplate jdbcTemplate;
@Resource
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
//添加
public void save(Person person) throws Exception{
jdbcTemplate.update("insert into person (name) values(?)",
new Object[]{person.getName()}, new int[]{java.sql.Types.VARCHAR});
}
}
<7、使用JdbcTemplate获取一条记录:
@Service @Transactional
public class PersonServiceBean implements PersonService {
private JdbcTemplate jdbcTemplate;
@Resource
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public Person getPerson(Integer id){
RowMapper rowMapper = new RowMapper(){
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Person person = new Person();
person.setId(rs.getInt("id"));
person.setName(rs.getString("name"));
return person;
}
};
return (Person)jdbcTemplate.queryForObject("select * from person where id=?",
new Object[]{id}, new int[]{java.sql.Types.INTEGER}, rowMapper);
}}
<8、使用JdbcTemplate获取多条记录:
@Service @Transactional
public class PersonServiceBean implements PersonService {
private JdbcTemplate jdbcTemplate;
@Resource
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Person> getPersons(){
RowMapper rowMapper = new RowMapper(){
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Person person = new Person();
person.setId(rs.getInt("id"));
person.setName(rs.getString("name"));
return person;
}
};
return jdbcTemplate.query("select * from person", rowMapper);
}
】
准备工作导入以下*.jar包
commons-dbcp.jar,commons-logging.jar,commons-pool.jar,spring.jar
commons-annotations.jar,mysql-connector-jarva-3.2.0-alpha-bin.jar
第一步:安装以上知识点搭建环境其中beans.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: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/tx http://www.springframework.org/schema/tx/spring-tx-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/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 配置数据源 -->
<bean id="dataSource" destroy-method="close">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="liyong"/>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="1"/>
<!-- 连接池的最大值 -->
<property name="maxActive" value="500"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="2"/>
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="1"/>
</bean>
<!-- 配置事务管理 -->
<tx:annotation-driven transaction-manager="txManager"/>
<!-- 指定这个事务管理的数据源 -->
<bean id="txManager" ref="dataSource"/>
</bean>
</beans>
第二步:编写一个java bean 类
public class Person {
private int id;
private String name;
public Person(){}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第三步:编写业务类及实现的接口
IPersonService。java PersonService。java
public interface IPersonService {
public abstract void add(int id,String name);
public abstract void delete(String name);
public abstract Person getObject(String name);
public abstract List<Person> getObjects();
}
@Transactional//这里表示这个类交个spring事务管理其中每个方法都在同一个事务中
public class PersonService implements IPersonService {
private DataSource source;//我们最好不好直接使用数据源使用JdbcTemplate来操作
private JdbcTemplate template;
public void setSource(DataSource source) {
this.template=new JdbcTemplate(source);
}
public void add(int id,String name)
{
template.update("insert into studentinfo(number,name)values(?,?)",new Object[]{id,name});
}
public void delete(String name)
{
template.update("delete from studentinfo where name=?",new Object[]{name});
}
public Person getObject(String name)
{
return (Person)template.queryForObject("select * from studentinfo where name=?", new Object[]{name},new int[]{java.sql.Types.VARCHAR}, new myRowMapper());
}
public List<Person> getObjects()
{
List<Person> list=template.query("select * from studentinfo", new myRowMapper());
return list;
}
}
第四步:这里是业务类中需要的一个行映射器类
public class myRowMapper implements RowMapper {
public Object mapRow(ResultSet set, int index) throws SQLException {
Person person=new Person(set.getInt("number"),set.getString("name"));
return person;
}
}
第五步:配置beans.xml文件为PersonService的属性DataSource注入值及把相应的bean交给spring
<bean id="person" ref="dataSource"></property>
</bean>
第六步:编写单元测试
public class PersonServiceTest {
@Test
public void TestAdd()
{
ApplicationContext cxt=new ClassPathXmlApplicationContext("beans.xml");
IPersonService service=(IPersonService)cxt.getBean("personService");
//service.add(3, "xiaowang");
//System.out.println(service.getObject("liyong").getName());
/*List<Person> list=service.getObjects();
Iterator<Person> iterator=list.iterator();
while (iterator.hasNext()) {
Person person = (Person) iterator.next();
System.out.println(person.getName());
}*/
service.delete("xiaowang");
List<Person> list=service.getObjects();
Iterator<Person> iterator=list.iterator();
while (iterator.hasNext()) {
Person person = (Person) iterator.next();
System.out.println(person.getName());
}
}
}
第七步:测试........
附:对于使用通配符和属性文件配置数据源
<?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: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/tx http://www.springframework.org/schema/tx/spring-tx-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/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="person" ref="dataSource"></property>
</bean>
<!-- 配置数据源 第一种-->
<!-- <bean id="dataSource" destroy-method="close">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="liyong"/>-->
<!-- 连接池启动时的初始值 -->
<!-- <property name="initialSize" value="1"/>-->
<!-- 连接池的最大值 -->
<!--<property name="maxActive" value="500"/>-->
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<!-- <property name="maxIdle" value="2"/>-->
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<!-- <property name="minIdle" value="1"/>
</bean>-->
<!-- 配置事务管理 -->
<!--<tx:annotation-driven transaction-manager="txManager"/>-->
<!-- 指定这个事务管理的数据源 -->
<!--
<bean id="txManager" ref="dataSource"/>
</bean>
-->
<!-- 配置数据源 第二种使用通配符-->
<!-- location="jdbc.properties"指定加载的属性文件 -->
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" destroy-method="close">
<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}"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}"/>
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="${minIdle}"/>
</bean>
</beans>
然后编写jdbc.properties属性文件
driverClassName=org.gjt.mm.mysql.Driver
url=jdbc\:mysql\://localhost\:3306/student?useUnicode\=true&characterEncoding\=UTF-8
username=root
password=liyong
initialSize=1
maxActive=500
maxIdle=2
minIdle=1
<!-- 使用xml来 配置事务 -->:
<bean id="txManager" ref="dataSource"/>
</bean>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* com.liyong.PersonService..*.*(..))"/>
<!-- 当拦截到方法后发出通知 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!-- 以下是拦截到的方法的事务配置 get*表示也get开头都是NOT_SUPPORTED不支持事务-->
<tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
<!-- 以下表示其它的方法也默认事务 -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>