基於註解的聲明式事務管理

POJO類
public class User {
    private Integer id;
    private String name;
    private int age;

    public User() {
    }

    public User(Integer id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    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;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "[User: id=" + id + ", name=" + name + ", age=" + age + "]";
    }

}
分頁查詢封裝類
public class QueryResult {
    private int count;
    private List list;

    public QueryResult(int count, List list) {
        this.count = count;
        this.list = list;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public List getList() {
        return list;
    }

    public void setList(List list) {
        this.list = list;
    }

}
增刪改查
@Repository
public class UserDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 保存
     * @param user
     */
    @Transactional(readOnly = true)
    public void save(final User user) {
        String sql = "insert into t_user(name, age) values (?, ?)";
        jdbcTemplate
                .update(sql, new Object[] { user.getName(), user.getAge() });
    }

    /**
     * 刪除
     * @param id
     */
    public void delete(Integer id) {
        String sql = "delete from t_user where id=?";
        jdbcTemplate.update(sql, new Object[] { id });
    }

    /**
     * 更新
     * @param user
     */
    public void update(User user) {
        String sql = "update t_user set name=?, age=? where id=?";
        jdbcTemplate.update(sql, new Object[] { user.getName(), user.getAge(),
                user.getId() });
    }

    /**
     * 根據id查詢一個數據
     * 
     * @param id
     * @return
     */
    public User getById(final Integer id) {
        String sql = "select name,age from t_user where id=?";
        return (User) jdbcTemplate.queryForObject(sql, new Object[] { id },
                new RowMapper() {
                    public Object mapRow(ResultSet rs, int rowNum)
                            throws SQLException {
                        String name = rs.getString(1);
                        int age = rs.getInt(2);
                        return new User(id, name, age);
                    }
                });
    }

    public void testGet(int id) {
        User user = getById(id);
        System.out.println(user);

        user = getById(id);
        System.out.println(user);
    }

    /**
     * 查詢總數量
     * 
     * @return
     */
    public int getCount() {
        String sql = "select count(*) from t_user";
        return jdbcTemplate.queryForInt(sql);
    }

    /**
     * 查詢所有
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<User> findAll() {
        String sql = "select * from t_user";
        return jdbcTemplate.query(sql, new RowMapper() {

            @Override
            public Object mapRow(ResultSet rs, int arg1) throws SQLException {
                int id = rs.getInt(1);
                String name = rs.getString(2);
                int age = rs.getInt(3);
                return new User(id, name, age);
            }
        });
    }

    /**
     * 查詢所有(分頁)
     * 
     * @param firstResult
     *            從哪一條開始
     * @param maxResult
     *            查詢幾條
     * @return
     */
    public QueryResult findAll(int firstResult, int maxResult) {
        int count = jdbcTemplate.queryForInt("select count(*) from t_user");
        String sql = "select * from t_user limit ?,?";
        List list = jdbcTemplate.query(sql, new Object[] { firstResult,
                maxResult }, new RowMapper() {

            @Override
            public Object mapRow(ResultSet as, int arg1) throws SQLException {
                int id = as.getInt(1);
                String name = as.getString(2);
                int age = as.getInt(3);

                return new User(id, name, age);
            }
        });
        return new QueryResult(count,list);
    }

}
測試類
public class UserDaoTest {

    private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml", getClass());
    private UserDao userDao = (UserDao) ac.getBean("userDao");

    @Test
    public void testSave_1() {
        User user = new User();
        user.setName("李四1");
        user.setAge(25);

        userDao.save(user);
    }

    @Test
    public void testSave_25() {
        for (int i = 1; i <= 25; i++) {
            User user = new User();
            user.setName("李四_" + i);
            user.setAge(i);

            userDao.save(user);
        }
    }

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

    @Test
    public void testUpdate() {
        User user = new User();
        user.setId(2); // 模擬一條記錄
        user.setName("李四222");
        user.setAge(25);

        userDao.update(user);
    }

    @Test
    public void testGetById() {
        User user = userDao.getById(2);
        System.out.println(user);
    }

    @Test
    public void testGetCount() {
        int count = userDao.getCount();
        System.out.println(count);
    }

    @Test
    public void testFindAll() {
        List<User> list = userDao.findAll();
        for (User user : list) {
            System.out.println(user);
        }
    }

    @Test
    public void testFindAllIntInt() {
        // 查詢
         QueryResult qr = userDao.findAll(0, 10); // 第1頁,每頁10條
//       QueryResult qr = userDao.findAll(10, 10); // 第2頁,每頁10條
//      QueryResult qr = userDao.findAll(20, 10); // 第3頁,每頁10條

        // 顯示結果
        System.out.println("總結果數:" + qr.getCount());
        for (User user : (List<User>) qr.getList()) {
            System.out.println(user);
        } 
    }
}
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"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    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/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 ">
    <!--  
    <context:property-placeholder location="classpath:cn/com/spring/k_property/jdbc.properties"/>
    -->
    <!-- 自動掃描與裝配bean -->
    <context:component-scan base-package="cn.com.spring.m_jdbc"></context:component-scan>
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:cn/com/spring/m_jdbc/jdbc.properties</value>
            </list>
        </property>
    </bean>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbcUrl}"></property>
        <property name="driverClass" value="${driverClass}"></property>
        <property name="user" value="${username}"></property>
        <property name="password" value="${password}"></property>
        <!-- 一些管理的配置 -->
        <!--初始化時獲取三個連接,取值應在minPoolSize與maxPoolSize之間。Default: 3 -->
        <property name="initialPoolSize" value="3"></property>
        <!--連接池中保留的最小連接數。Default: 3 -->
        <property name="minPoolSize" value="3"></property>
        <!--連接池中保留的最大連接數。Default: 15 -->
        <property name="maxPoolSize" value="5"></property>
        <!--當連接池中的連接耗盡的時候c3p0一次同時獲取的連接數。Default: 3 -->
        <property name="acquireIncrement" value="3"></property>
        <!--最大空閒時間,1800秒內未使用則連接被丟棄,若爲0則永不丟棄。Default: 0 -->
        <property name="maxIdleTime" value="1800"></property>
    </bean>

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


    <!-- 三、配置聲明式事務管理 -->


    <!-- 聲明“事務管理器” -->
    <bean id="dsTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- ==== 基於註解的方式配置事務 ==== -->
    <tx:annotation-driven transaction-manager="dsTransactionManager"/>


</beans>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章