简体   繁体   中英

Spring 3 Annotations: xml-less Declarative Transaction Management

I am creating a purely annotation driven (xml-less) spring 3 application following the tutorial here

And here's my configuration file

@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
    DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
    driverManagerDataSource.setDriverClassName("org.postgresql.Driver");
    driverManagerDataSource.setUrl("jdbc:postgresql://localhost:5432/test");
    driverManagerDataSource.setUsername("postgres");
    driverManagerDataSource.setPassword("gayle");
    return driverManagerDataSource;
}

@Bean(name = "studentJDBCTemplate")
public StudentJDBCTemplate studentJDBCTemplate() {
    StudentJDBCTemplate studentJDBCTemplate = new StudentJDBCTemplate();
    studentJDBCTemplate.setDataSource(dataSource());
    studentJDBCTemplate.setDataSourceTransactionManager(dataSourceTransactionManager());
    studentJDBCTemplate.setJdbcTemplate(new JdbcTemplate());
    return studentJDBCTemplate;
}

@Bean
public DataSourceTransactionManager dataSourceTransactionManager() {
    DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
    dataSourceTransactionManager.setDataSource(dataSource());
    return dataSourceTransactionManager;
}

Now I'm trying to do declarative transaction management hence my create() method inside StudentJDBCTemplate

public void create(String name, Integer age) {
    System.out.println("Creating!");
    String SQL = "insert into Student (name, age) values (?, ?)";
    jdbcTemplate.update(SQL, name, age);
    System.out.println("Created Record Name=" + name + " Age=" + age);
}

does not programmatically call the transaction manager.

How do I achieve this? Do I have to declare an @Aspect to do this? Is there any annotation that can automatically configure when to commit transactions?

You want to use the @Transactional annotation. Here's the documentation for it. Specifically, go to section 10.5.1. All you need to do is annotate the methods you want to have a transaction wrapped around with the annotation. With the annotation's values you can specify anything you want about the type of transaction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM