import com.apress.prospring3.ch13.service.ContactService;
public class TxDeclarativeSample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:tx-declarative-app-context.xml");
ctx.refresh();
ContactService contactService = ctx.getBean("contactService",
ContactService.class);
// Testing findAll() method
List<Contact> contacts = contactService.findAll();
for (Contact contact: contacts) {
System.out.println(contact);
}
// Testing save() method
Contact contact = contactService.findById(1l);
contact.setFirstName("Peter");
contactService.save(contact);
System.out.println("Contact saved successfully");
// Testing countAll() method
System.out.println("Contact count: " + contactService.countAll());
}
}
We will leave you to test the program and observe the output for transaction-related operations that
Spring and Hibernate has performed. Basically, they are the same as the annotation example.
Using Programmatic Transactions
The third option is to control the transaction behavior programmatically. In this case, we have two
options. The first one is to inject an instance of PlatformTransactionManager into the bean and interact
with the transaction manager directly. Another option is to use the Spring-provided
TransactionTemplate class, which simplifies your work a lot. In this section, we will demonstrate using
the TransactionTemplate class. To make it simple, we will just focus on implementing the
ContactService.countAll() method.
Listing 13-21 shows the XML configuration for using programmatic transaction (tx-programmatic-
app-context.xml).
Listing 13-21. Spring Configuration for Programmtic Transaction Management
<?xml version="1.0" encoding="UTF-8"?>
<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"
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home