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.先对数据库进行数据添加方便程序运行后的出效果
运行前
运行后