Java mac idea spring的使用03

1. spring容器整合jdbc,实现数据库操作

  1. 创建User类

public class User {
    private Integer id;
    private String 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() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

  1. 创建UserDao接口
public interface UserDao {
    // 增
    public void save(User user) throws PropertyVetoException;

    // 删
    public void delete(Integer id);

    // 改
    public void update(User user);

    // 查
    public User getUserById(Integer id);

    // 查
    public int getTotalCount();

    // 查
    public List<User> getAllUser();
}

  1. 创建userDao的实现类,实现接口
public class UserDaoImpl implements UserDao{

    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void save(User user)  {

        String sql = "insert into t_user values(null, ?)";

        jdbcTemplate.update(sql, user.getName());
    }

    @Override
    public void delete(Integer id) {

        String sql = "delete from t_user where id = ? ";

        jdbcTemplate.update(sql, id);
    }

    @Override
    public void update(User user) {

        String sql = "update t_user set name = ? where id = ? ";

        jdbcTemplate.update(sql, user.getName(), user.getId());
    }

    @Override
    public User getUserById(Integer id) {

        String sql = "select * from t_user where id = ? ";

         return jdbcTemplate.queryForObject(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {

                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                return user;
            }
        }, id);
    }

    @Override
    public int getTotalCount() {
        String sql = "select count(*) from t_user";

        int count = jdbcTemplate.queryForObject(sql, Integer.class);

        return count;
    }

    @Override
    public List<User> getAllUser() {

        String sql = "select * from t_user";

        List<User> list = jdbcTemplate.query(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                return user;
            }
        });
        return list;
    }
  1. 将jdbc连接池、jdbcDataSource、userDao的实现类,配置到spring
<!--将连接池放入spring 容器-->
    <bean name="jdbcDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="jdbc:mysql://xxx.206.7.239/xiaobang"></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456789"></property>
    </bean>

    <!--将jdbcDataSource 放入spring容器-->
    <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="jdbcDataSource"></property>
    </bean>

    <!--将userDao的实现类放入spring容器-->
    <bean name="userDao" class="daoImpl.UserDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

2. 继承JdbcDaoSupport整合jdbc,实现数据库操作

准备阶段还是一样的,只写不一样的地方
1.dao的实现类中,直接继承JdbcDaoSupport ,不再需要我们自己创建JdbcTemplate

public class UserDaoImpl extends JdbcDaoSupport implements UserDao{

    
    @Override
    public void save(User user)  {

        String sql = "insert into t_user values(null, ?)";

        super.getJdbcTemplate().update(sql, user.getName());
    }

    @Override
    public void delete(Integer id) {

        String sql = "delete from t_user where id = ? ";

        super.getJdbcTemplate().update(sql, id);
    }

    @Override
    public void update(User user) {

        String sql = "update t_user set name = ? where id = ? ";

        super.getJdbcTemplate().update(sql, user.getName(), user.getId());
    }

    @Override
    public User getUserById(Integer id) {

        String sql = "select * from t_user where id = ? ";

         return super.getJdbcTemplate().queryForObject(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {

                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                return user;
            }
        }, id);
    }

    @Override
    public int getTotalCount() {
        String sql = "select count(*) from t_user";

        int count = super.getJdbcTemplate().queryForObject(sql, Integer.class);

        return count;
    }

    @Override
    public List<User> getAllUser() {

        String sql = "select * from t_user";

        List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                return user;
            }
        });
        return list;
    }
  1. 配置文件
<!--将连接池放入spring 容器-->
    <bean name="jdbcDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="jdbc:mysql://xxx.206.7.239/xiaobang"></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456789"></property>
    </bean>


    <!--将userDao的实现类放入spring容器-->
    <bean name="userDao" class="daoImpl.UserDaoImpl">
        <property name="dataSource" ref="jdbcDataSource"></property>
    </bean>

3. 通过properties文件来配置spring的jdbc

  1. 创建db.properties文件
jdbc.jdbcUrl=jdbc:mysql://xxx.206.7.239/xiaobang
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456789
  1. 修改applicationContext.xml配置文件
<!--指定spring读取db.properties-->
    <context:property-placeholder location="classpath:db.properties"/>


    <!--将连接池放入spring 容器-->
    <bean name="jdbcDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

4. xml配置spring aop 事务

4.1 . 前期准备

  1. 创建t_account 表


    Snip20180803_17.png

创建对应的Account类

public class Account {
    private Integer id;
    private String name;
    private Double money;

    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 Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

  1. 创建AccountDao接口
public interface AccountDao {

    public void rollInMoney(Integer id, Double money);

    public void rollOutMoney(Integer id, Double money);


    // 增
    public void save(Account account) throws PropertyVetoException;

    // 改
    public void update(Account account);
}
  1. 创建AccountDaoImpl,接口实现类
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

    @Override
    public void rollInMoney(Integer id, Double money) {

        String sql = "update t_account set money = money + ? where id = ? ";

        super.getJdbcTemplate().update(sql, money, id);
    }

    @Override
    public void rollOutMoney(Integer id, Double money) {

        String sql = "update t_account set money = money - ? where id = ? ";

        super.getJdbcTemplate().update(sql, money, id);
    }

    @Override
    public void save(Account account) throws PropertyVetoException {

        String sql = "insert into t_account values(null, ?, ?)";

        super.getJdbcTemplate().update(sql, account.getName(), account.getMoney());
    }

    @Override
    public void update(Account account) {
        String sql = "update t_account set name = ?, money = ? where id = ? ";

        super.getJdbcTemplate().update(sql, account.getName(), account.getMoney(), account.getId());
    }

}
  1. 创建AccountService接口
public interface AccountService {

    public void transfer(Integer from, Integer to, Double money);
}

  1. 创建AccountServiceImpl接口实现类
public class AccountServiceImpl implements AccountService {

    @Resource(name = "accountDao")
    private AccountDao ad;

    @Override
    public void transfer(Integer from, Integer to, Double money) {

        ad.rollOutMoney(from, money);

//        int i = 1 / 0;

        ad.rollInMoney(to, money);
    }

    public AccountDao getAd() {
        return ad;
    }

    public void setAd(AccountDao ad) {
        this.ad = ad;
    }
}

4.2 书写配置文件

  1. 准备连接池
<!--指定spring读取db.properties-->
    <context:property-placeholder location="classpath:db.properties"/>


    <!--将连接池放入spring 容器-->
    <bean name="jdbcDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
  1. 添加事务核心管理器
<!--事务核心管理器,封装了所有事务操作,依赖于连接池-->
    <bean name="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="jdbcDataSource"></property>
    </bean>
  1. 配置事务通知
 <!--配置事务通知-->
    <tx:advice id="transactionInterceptor" transaction-manager="dataSourceTransactionManager">
        <tx:attributes>
            <!-- 以方法为单位,指定方法应用什么事务属性
                        isolation:隔离级别
                        propagation:传播行为
                        read-only:是否只读
                     -->
            <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>

            <!--增-->
            <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
            <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>

            <!--改-->
            <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
            <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>

            <!--删-->
            <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
            <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>

            <!--查-->
            <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
            <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>

        </tx:attributes>
    </tx:advice>
  1. 织入通知
<!--配置织入-->
    <aop:config>

        <aop:pointcut id="transactionPc" expression="execution(public void service.AccountServiceImpl.transfer(..))"/>

        <aop:advisor advice-ref="transactionInterceptor" pointcut-ref="transactionPc"/>

    </aop:config>
  1. 将其他类放入spring容器中
<!--将userDao的实现类放入spring容器-->
    <bean name="userDao" class="daoImpl.UserDaoImpl">
        <property name="dataSource" ref="jdbcDataSource"></property>
    </bean>

    <!--将accountDao的实现类放入spring容器-->
    <bean name="accountDao" class="daoImpl.AccountDaoImpl">
        <property name="dataSource" ref="jdbcDataSource"></property>
    </bean>

    <!--将service的实现类放入spring容器-->
    <bean name="accountService" class="service.AccountServiceImpl">
        <property name="ad" ref="accountDao"></property>
    </bean>

4.3 测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo2 {

    @Resource(name = "accountDao")
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Resource(name = "accountService")
    private AccountService accountService;

    // 改
    @Test
    public void testFunc01() throws PropertyVetoException {

        Account account = new Account();
        account.setId(2);
        account.setName("lisi");
        account.setMoney(1000d);

        accountDao.update(account);
    }

    @Test
    public void testFunc02() {

        accountService.transfer(1,2, 100d);
    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

}

5. 使用注解配置aop事务

5.1 配置文件

<!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
        <property name="dataSource" ref="jdbcDataSource" ></property>
    </bean>
    

    <!--开启使用注解管理事务-->
    <tx:annotation-driven/>

5.2 实现将通知织入的注解

    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = false)
    public void transfer(Integer from, Integer to, Double money) {

        ad.rollOutMoney(from, money);

//        int i = 1 / 0;

        ad.rollInMoney(to, money);
    }

5.3 测试


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:jdbcTemplate/applicationContext.xml")
public class Demo3 {


    @Resource(name = "accountService")
    private AccountService accountService;


    @Test
    public void testFunc() {

        accountService.transfer(1,2, 100d);
    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }
}

5.4 注解放在类和方法上

// 给所有方法加注解
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = false)
public class AccountServiceImpl implements AccountService {

    @Resource(name = "accountDao")
    private AccountDao ad;

    @Override
    // 单独给某个方法加不同的注解
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = true)
    public void transfer(Integer from, Integer to, Double money) {

        ad.rollOutMoney(from, money);

//        int i = 1 / 0;

        ad.rollInMoney(to, money);
    }


    public AccountDao getAd() {
        return ad;
    }

    public void setAd(AccountDao ad) {
        this.ad = ad;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,656评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,810评论 6 342
  • 郭相麟 生活是一个修炼的道场,所遇见的人和事是一种悟道的过程! 世上万物接近极致,要想在生活的道场中悟出智慧...
    郭相麟阅读 545评论 0 0