Spring5 使用jDBCTemplate连接Mysql8+SQLyog环境搭建的详细步骤

0.引入依赖包(所有能用到或者用不到的jar包)

下载链接后续整理或私聊

1.配置xml文件

<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--        开启扫描-->
    <context:component-scan base-package="com.lxj.springtx"></context:component-scan>
    <!--数据库连接-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="jdbc:mysql://localhost:3306/user_db"></property>
        <property name="username" value="root"></property>
        <property name="password" value="aha233"></property>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
    </bean>
    <!--    JdbcTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--    注入dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

2.创建Dao接口声明对数据库操作的抽象方法

public interface UserDao {
    public void addMoney();
    public void reduceMoney();
}

3.创建Dao的实现类并用@Repository创建对象,创建jdbctemplate属性,实现抽象方法

@Repository
public class UserDaoImpl implements UserDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void addMoney() {
        String sql =  "update t_account set money=money+? where username=?";
        jdbcTemplate.update(sql,100,"mary");
    }

    @Override
    public void reduceMoney() {
        String sql =  "update t_account set money=money-? where username=?";
        jdbcTemplate.update(sql,100,"lucy");
    }
}

4.创建Service实现类 @Service注入Dao实现类的对象 调用其方法实现业务逻辑

@Service
public class UserService {
    @Autowired
    private UserDaoImpl userDao;
    public void accountMoney(){
        userDao.addMoney();
        userDao.reduceMoney();
    }
}

5.测试,读取xml文件getbean创建Service对象调用方法。

public class DemoTest {
    @Test
    public void txTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("springtx.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.accountMoney();
    }
}

6.先对数据库进行数据添加方便程序运行后的出效果

运行前

 运行后

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值