1、架包:commons-dbcp.jar commons-pool.jar mysql-connector-java-5.0.7-bin.jar
2、引入命名空间,如下:
xmlns:tx=http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
3、配置数据源,如下:
<!-- 配置数据源 --> <context:property-placeholder location="jdbc.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 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、配置事务:需要在xml配置文件中引入声明事务的tx命名空间,事务配置有两种方式:注解和基于xml配置方式
1)采用注解
1.事务配置
<!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/><!-- 注入数据源 --> </bean>
2.配置事务处理器
<!-- 采用 @transactionl 注解方式使用事务 --> <tx:annotation-driven transaction-manager="transactionManager"/>
3.将UserServiceImp.java交给容器
<!-- 将UserServiceImp类交个spring容器管理 --> <bean id="userServiceImp" class="com.qh.service.imp.UserServiceImp"> <!-- UserServiceImp类中set方法的对象 ,采用JdbcTemplete--> <property name="dataSource" ref="dataSource"/> </bean>
到此注解配置结束
2)采用xml配置
1.引入AOP命名空间
xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
2.配置事务管理
<!-- 基于xml文件配置事务 --> <aop:config> <aop:pointcut id="myPointCut" expression="execution(* com.qh.service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointCut"/> </aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" propagation="NOT_SUPPORTED"/> <tx:method name="*"/> </tx:attributes> </tx:advice>
到此xml文件配置结束,详细参见下载
5、基于注解的核心代码:(关于xml文件配置代码看下载)
UserBean.java
package com.qh.bean; public class UserBean { private int id; private String username; private String password; private String email; public UserBean(){} public UserBean(String username, String password, String email) { this.username = username; this.password = password; this.email = email; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
UserService.java
package com.qh.service; import java.util.List; import com.qh.bean.UserBean; public interface UserService { //保存 public void save(UserBean userBean); //更新 public void update(UserBean userBean); //根据id查询 public UserBean getUserBeanById(Integer id); //获取所有记录 public List<UserBean> getUserBeans(); //根据id删除记录 public void delete(Integer id); }
UserServiceImp.java
package com.qh.service.imp; import java.util.List; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.annotation.Transactional; import com.qh.bean.UserBean; import com.qh.service.UserService; @Transactional //保证同一个方法中的所有操作都在同一个事务中执行 public class UserServiceImp implements UserService { // 获取数据源,提供set方法,将数据源注入到bean中 private JdbcTemplate jdbcTemplate; public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } public void save(UserBean userBean) { String sql = "insert into user(username,password,email) values(?,?,?)"; jdbcTemplate.update(sql, new Object[] { userBean.getUsername(), userBean.getPassword(), userBean.getEmail() }, new int[] { java.sql.Types.VARCHAR, java.sql.Types.VARCHAR, java.sql.Types.VARCHAR }); } public void update(UserBean userBean) { String sql = "update user set username=?,password=?,email=? where id=?"; jdbcTemplate.update(sql, new Object[] { userBean.getUsername(), userBean.getPassword(), userBean.getEmail(), userBean.getId() }, new int[] { java.sql.Types.VARCHAR, java.sql.Types.VARCHAR, java.sql.Types.VARCHAR, java.sql.Types.INTEGER }); } public UserBean getUserBeanById(Integer id) { String sql = "select * from user where id=?"; return (UserBean)jdbcTemplate.queryForObject(sql, new Object[] { id }, new int[] { java.sql.Types.INTEGER }, new UserRowMapper());//回调; } @SuppressWarnings("unchecked") public List<UserBean> getUserBeans() { String sql = "select * from user"; return (List<UserBean>)jdbcTemplate.query(sql,new UserRowMapper());//回调; } public void delete(Integer id) { String sql = "delete from user where id=?"; jdbcTemplate.update(sql, new Object[] { id }, new int[] {java.sql.Types.INTEGER }); } }
UserRowMapper.java
package com.qh.service.imp; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.qh.bean.UserBean; public class UserRowMapper implements RowMapper { // 当外部调用此方法时,rs.next()已经调用 public Object mapRow(ResultSet rs, int index) throws SQLException { UserBean userBean = new UserBean(rs.getString("username"), rs.getString("password"), rs.getString("email")); userBean.setId(rs.getInt("id")); return userBean; } }
UserTest.java
package com.qh.test; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.qh.bean.UserBean; import com.qh.service.UserService; public class UserTest { private static UserService userServiceImp; @BeforeClass public static void init(){ try { ApplicationContext apx=new ClassPathXmlApplicationContext("beans.xml"); userServiceImp=(UserService) apx.getBean("userServiceImp");//注意 } catch (BeansException e) { e.printStackTrace(); } } @Test public void getUserBeans() { for(UserBean temp : userServiceImp.getUserBeans()){ System.out.println(temp.getUsername()); } } @Test public void delete(){ userServiceImp.delete(3); } @Test public void save(){ UserBean userBean=new UserBean("aa", "aa", "qq.com"); userServiceImp.save(userBean); } @Test public void update(){ UserBean userBean=new UserBean("bb", "bb", "qq.com"); userBean.setId(4); userServiceImp.update(userBean); } @Test public void getUserById(){ System.out.println(userServiceImp.getUserBeanById(1).getUsername()); } }
至此,基于注解的开发结束了。
附:使用properties文件引入
将beans.xml中的数据源的配置放到jdbc.properties中
driverClassName=org.gjt.mm.mysql.Driver url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8 username=root password=123 initialSize=1 maxActive=500 maxIdle=2 minIdle=1
然后在beans.xml中引用:${driverClassName}
在beans.xml中需要引入命名空间
xmlns:context="http://www.springframework.org/schema/context" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
该命名空间支持以下内容
<context:property-placeholder location="jdbc.properties"/>
此内容是将jdbc.properties引入到xml文件中
配置结束