简体   繁体   English

Spring 3批注:无xml声明式事务管理

[英]Spring 3 Annotations: xml-less Declarative Transaction Management

I am creating a purely annotation driven (xml-less) spring 3 application following the tutorial here 我将按照此处的教程创建纯注释驱动(无xml)的Spring 3应用程序

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 现在,我正在尝试进行declarative transaction management因此,我在StudentJDBCTemplate create()方法

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? 我必须声明一个@Aspect来做到这一点吗? Is there any annotation that can automatically configure when to commit transactions? 是否有任何注释可以自动配置何时提交事务?

You want to use the @Transactional annotation. 您要使用@Transactional批注。 Here's the documentation for it. 这是它的文档。 Specifically, go to section 10.5.1. 具体来说,请转到第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. 使用注释的值,您可以指定有关事务类型的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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