📅  最后修改于: 2023-12-03 15:01:33.174000             🧑  作者: Mango
在开发中,事务是非常常见的概念,特别是在涉及到数据修改的操作中。Java提供了很多方便的方式来处理事务,本文将提供一个Java事务示例,涉及如何使用Spring框架来处理事务。
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
</dependencies>
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/testdb?useSSL=false
jdbc.username=root
jdbc.password=123456
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT INTO `test` (`name`) VALUES ('aaa'), ('bbb'), ('ccc');
public interface TestDAO {
public void insert(String name);
}
@Repository
public class TestDAOImpl implements TestDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
@Transactional
public void insert(String name) {
String sql = "insert into test(name) values(?)";
jdbcTemplate.update(sql, name);
}
}
注解说明:
public interface TestService {
public void insert(String name);
}
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestDAO testDAO;
@Transactional
public void insert(String name) {
testDAO.insert(name);
}
}
注解说明:
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
TestService testService = (TestService) ctx.getBean(TestService.class);
testService.insert("ddd");
List<Map<String, Object>> list =
ctx.getBean(JdbcTemplate.class).queryForList("select * from test");
for (Map<String, Object> map : list) {
System.out.println(map.get("name"));
}
};
}
}
注解说明:
本文提供了一个Java事务示例,涉及如何使用Spring框架来处理事务。通过学习本文,可以更好地理解Java的事务概念,以及如何使用Spring框架来有效地处理事务操作。