Skip to content

Instantly share code, notes, and snippets.

@verydapeng
Last active February 6, 2017 03:04
Show Gist options
  • Save verydapeng/750be65f73a9f2f3abcee31d54477248 to your computer and use it in GitHub Desktop.
Save verydapeng/750be65f73a9f2f3abcee31d54477248 to your computer and use it in GitHub Desktop.
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
import java.util.List;
@Configuration
@EnableTransactionManagement
public class TxApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(TxApplication.class, args);
System.out.println("\r\n\r\n");
MyService service = context.getBean(MyService.class);
try {
service.save();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(service.query());
}
@Bean
ApplicationRunner init(JdbcTemplate template) {
return args -> template.update("CREATE TABLE test (id INT PRIMARY KEY)");
}
@Bean
// comment out this bean to see exception
PlatformTransactionManager platformTransactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean
DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.build();
}
@Bean
JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
@Bean
MyService myService() {
return new MyService();
}
}
class MyService {
@Autowired
JdbcTemplate jdbcTemplate;
List<Integer> query() {
return jdbcTemplate.queryForList("select id from test", Integer.class);
}
@Transactional
public void save() {
jdbcTemplate.update("insert into test values (1)");
if (Math.random() > 0.5) {
throw new RuntimeException("Throwing Exception");
} else {
System.out.println("Insert should work");
}
}
}
@verydapeng
Copy link
Author

output of the program

When exception is thrown

Throwing Exception
[]

When no exception

Insert should work
[1]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment