This document provides an overview of Spring's transaction management capabilities. It discusses how Spring provides a uniform transaction management API that can work with various transaction technologies like JDBC, Hibernate, JPA etc. It also describes how transactions can be handled programmatically using the TransactionTemplate or directly through the transaction manager. Finally, it covers Spring's declarative transaction support using XML or annotations.
Spring Data is a high level SpringSource project whose purpose is to unify and ease the access to different kinds of persistence stores, both relational database systems and NoSQL data stores.
Java and Spring Data JPA: Easy SQL Data Access
Abstract
Presenter: Miya W. Longwe, MBA, MSE, Tech Lead, Staples, Inc, Framingham MA 01702
Accessing data repositories in various applications programming languages typically involves writing of tedious boilerplate lines of code. Some application development frameworks such as Spring have tried to make the experience more succinct by providing abstraction layers such as HibernateTemplate and JdbcTemplate, etc. Despite these APIs, the developers still spend a lot time writing repetitive code than concentrating on implementing business requirements. Developers at Spring, led by Oliver Gierke, introduced Spring Data JPA which “aims to significantly improve the implementation of data access layers by reducing the effort to the amount that's actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically”.
Spring Data JPA provides a powerful, out-of-the-box alternative to creating your own DAO framework. You declare custom repository operations on an interface, and the framework generates dynamic implementations (not code generation) automatically, based on conventions around method names. As part of the presentation, we'll also review a demo to look at Spring Java configuration (as opposed to XML configuration), and investigate the @Profile annotation – configuration details which may make life a bit easier in various ways when setting up unit testing of our repository classes, using out-of-the-box alternative to creating DAO framework, how to create custom repositories, pagination and support for custom queries among other features.
Presenter's Bio
Miya W. Longwe is a Senior Software Engineer and Tech Lead at Staples, Inc. where he is currently working on an initiative to re-platform the company’s ecommerce architecture to offer platform-driven, modular products that can be quickly customized, enhanced, and branded as needed.
Miya has been a software professional since 1997. His 16 years software development career includes working for large companies to small startups, building solutions for enterprises and consumers, working with a broad range of technologies.
Miya Longwe is a hands-on java developer. He believes that in order to be a relevant and effective software developer one needs to remain a deeply knowledgeable, up-to-date, and productive software developer. His research interests include model-driven engineering, domain specific languages, test driven development and project risk management.
Miya graduated from the University of Malawi (Lilongwe, Malawi) and has an MBA from the University of Wales Cardiff Business School (Wales, UK) and a Masters in Software Engineering from Brandeis University (MA, USA).
Occasionally, Miya can be spotted fishing the banks of the south shore (MA) with his two boys, William and Daniel.
Spring Data is a high level SpringSource project whose purpose is to unify and ease the access to different kinds of persistence stores, both relational database systems and NoSQL data stores.
Java and Spring Data JPA: Easy SQL Data Access
Abstract
Presenter: Miya W. Longwe, MBA, MSE, Tech Lead, Staples, Inc, Framingham MA 01702
Accessing data repositories in various applications programming languages typically involves writing of tedious boilerplate lines of code. Some application development frameworks such as Spring have tried to make the experience more succinct by providing abstraction layers such as HibernateTemplate and JdbcTemplate, etc. Despite these APIs, the developers still spend a lot time writing repetitive code than concentrating on implementing business requirements. Developers at Spring, led by Oliver Gierke, introduced Spring Data JPA which “aims to significantly improve the implementation of data access layers by reducing the effort to the amount that's actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically”.
Spring Data JPA provides a powerful, out-of-the-box alternative to creating your own DAO framework. You declare custom repository operations on an interface, and the framework generates dynamic implementations (not code generation) automatically, based on conventions around method names. As part of the presentation, we'll also review a demo to look at Spring Java configuration (as opposed to XML configuration), and investigate the @Profile annotation – configuration details which may make life a bit easier in various ways when setting up unit testing of our repository classes, using out-of-the-box alternative to creating DAO framework, how to create custom repositories, pagination and support for custom queries among other features.
Presenter's Bio
Miya W. Longwe is a Senior Software Engineer and Tech Lead at Staples, Inc. where he is currently working on an initiative to re-platform the company’s ecommerce architecture to offer platform-driven, modular products that can be quickly customized, enhanced, and branded as needed.
Miya has been a software professional since 1997. His 16 years software development career includes working for large companies to small startups, building solutions for enterprises and consumers, working with a broad range of technologies.
Miya Longwe is a hands-on java developer. He believes that in order to be a relevant and effective software developer one needs to remain a deeply knowledgeable, up-to-date, and productive software developer. His research interests include model-driven engineering, domain specific languages, test driven development and project risk management.
Miya graduated from the University of Malawi (Lilongwe, Malawi) and has an MBA from the University of Wales Cardiff Business School (Wales, UK) and a Masters in Software Engineering from Brandeis University (MA, USA).
Occasionally, Miya can be spotted fishing the banks of the south shore (MA) with his two boys, William and Daniel.
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...Cloudera, Inc.
Working with Hadoop does not always mean starting from scratch. In this session, you’ll learn how to leverage your existing investments in tools and skills to accelerate your Hadoop development. Learn from experts as they walk you step-by-step through the conversion of an existing ETL process to use Big Data.
For More information, refer to Java EE 7 performance tuning and optimization book:
The book is published by Packt Publishing:
http://www.packtpub.com/java-ee-7-performance-tuning-and-optimization/book
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...Cloudera, Inc.
Working with Hadoop does not always mean starting from scratch. In this session, you’ll learn how to leverage your existing investments in tools and skills to accelerate your Hadoop development. Learn from experts as they walk you step-by-step through the conversion of an existing ETL process to use Big Data.
For More information, refer to Java EE 7 performance tuning and optimization book:
The book is published by Packt Publishing:
http://www.packtpub.com/java-ee-7-performance-tuning-and-optimization/book
Introduction to JDBC and database access in web applicationsFulvio Corno
Introduction to the JDBC standard and best practices for database access from Web Applications.
Materiale realizzato per il corso di Sistemi Informativi Aziendali del Politecnico di Torino - http://bit.ly/sistinfo
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?XfilesPro
Worried about document security while sharing them in Salesforce? Fret no more! Here are the top-notch security standards XfilesPro upholds to ensure strong security for your Salesforce documents while sharing with internal or external people.
To learn more, read the blog: https://www.xfilespro.com/how-does-xfilespro-make-document-sharing-secure-and-seamless-in-salesforce/
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
4. Architecture & Modules
Dependency Injection & IOC
Spring configuration
Example
5.
6.
7. IoC and DI features based on
the BeanFactory container
concept
Powerful
language
for querying
and
manipulating
an
object graph
at
runtime
Build on the base of Beans and
Core. Provide way to access
objects, support for i18n, resource
loading
8. JDBC –
provides
an abstraction
layer
Object/XML
mapping
implementations
like JAXB or
XStream
Programmatic or
declarative
transaction
management.
ORM –
provides
integration
layers
for popular
ORM
APIs like JPA,
Hibernate or
iBatis. Support
of
declarative
transaction
management.
9. Instead of objects invoking other objects, the
dependant objects are added through an
external entity/container.
Dependencies are “injected” by container
during runtime.
Beans define their dependencies through
constructor arguments or properties
10. Implementation of the Inversion of Control
pattern
BeanFactory responsible for instantiating all
components based on a configuration
13. public class BookDemoServiceImpl implements BookDemoService {
private BookDemoDao dao;
public void addPublisherToBook(Book book) {
String isbn = book.getIsbn();
if (book.getPublisher() == null && isbn != null) {
Publisher publisher = dao.findPublisherByIsbn(isbn);
book.setPublisher(publisher);
}
}
public void setBookDemoDao(BookDemoDao dao) {
this.dao = dao;
}
}
14. 14
We have so far seen:
◦ Spring Architecture and Core Module
◦ IOC & Dependency Injection
◦ Spring configuration’s and Examples of
Dependency Injection in Spring
15.
16. Learning Objectives
◦ Learn core functionality of Spring’s JDBC framework
◦ Understand templates and callback mechanism
◦ Understand How Spring provides a way to actually
model database operations as objects
17. Action Spring You
Define connection
parameters.
X
Open the connection. X
Specify the SQL statement. X
Declare parameters and
X
provide parameter values
Prepare and execute the
statement.
X
Set up the loop to iterate
through the results (if any).
X
Do the work for each
iteration.
X
Process any exception. X
Handle transactions. X
Close the connection,
X
statement and resultset.
18. public void GettingRows() {
Connection conn=null;
Statement stmt=null;
Resultset rset=null;
try{
Declare connection parameters
conn = dataSource.getConnection();
stmt = conn.createStatement ();
rset = stmt.executeQuery ("select empno, ename,job from
emp");
while (rset.next()) {
System.out.print (rset.getString (1));
}
} catch (SQLException e) {
LOGGER.error(e); throw e;
}
finally{
//code to clean up resources
Open connection
Create statement
Execute statement
Iterate over resultset
Handle exceptions
clean up resources
19. Spring separates the fixed and variant parts
of the data access process into two distinct
classes:
◦ Templates: manage the fixed part of the process
like controlling transactions, managing resources,
handling exceptions etc
◦ Callbacks: define implementation details, specific to
application ie. Creating statements, binding
parameters etc
19
20. There are a number of options for selecting
an approach to form the basis for your JDBC
database access
◦ JdbcTemplate
◦ NamedParameterJdbcTemplate
◦ SimpleJdbcTemplate
◦ SimpleJdbcInsert and SimpleJdbcCall
◦ RDBMS Objects including MappingSqlQuery,
20
SqlUpdate and StoredProcedure
21. 21
Central class in JDBC framework
Manages all database communication and
exception handling
Based on template style of programming; some
calls are handled entirely by JdbcTemplate while
others require the calling class to provide
callback methods that contain implementation
for parts of the JDBC workflow
22. To work with data from a database, we need to obtain a
connection to the database - through a DataSource
22
Many implementations of DataSource exist. Eg:
◦ BasicDataSource
◦ PoolingDataSource
◦ SingleConnectionDataSource
◦ DriverManagerDataSource
The datasource can be programmatically configured. Eg
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driver); ds.setUrl(url);
ds.setUsername(username); ds.setPassword(password);
25. JdbcTemplate jt = new JdbcTemplate(dataSource);
Some examples:
int count = jt.queryForInt(“select count(*) from emp”);
String name = (String) jt.queryForObject("select name from mytable
where empno=1022", String.class);
List rows = jt.queryForList("select * from mytable");
Object params[] = new Object[]{new Double(1000.0)};
List rows1 = jt.queryForList(“Select * from emp where sal >
?”,params);
25
26. public class ExecuteAStatement {
private JdbcTemplate jt, DataSource dataSource;
public void doExecute() {
jt = new JdbcTemplate(dataSource);
jt.execute("create table mytable (id integer, name
varchar(100))");
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
27. Some examples:
int x=jt.update(“insert into Book(id,name) values(1,’Core Java’)”);
int x=jt.update(“Update Book set name=‘Advanced Java’ where
id=?”, new Object[]{new Integer(3)});
int x=jt.update(“Delete from Book where id=2”);
String sql = “insert into person(id,fname,lname) values (?,?,?)”;
Object[] params = new Object[]{ p.getId(), p.getFname(),
27
p.getLname()};
int[] types = new Int[]{Types.INTEGER, Types.VARCHAR,
Types.VARCHAR};
int count = jdbcTemplate.update(sql,params,types);
28. JdbcTemplate class supports the callback
methods concept for performing different
SQL operations.
Callback methods allow the developer to
manage database operations using a higher
level of abstraction.
Interfaces that can be implemented to handle
the returned rows are :
◦ ResultSetExtractor
◦ RowCallbackHandler
◦ RowMapper
28
29. The NamedParameterJdbcTemplate class add
supports for programming JDBC statements
using named parameters, as opposed to
programming JDBC statements using only
classic placeholder ('?') arguments.
The NamedParameterJdbcTemplate class
wraps a JdbcTemplate, and delegates to the
wrappedJdbcTemplate to do much of its
work.
30. // some JDBC-backed DAO class...
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.namedParameterJdbcTemplate = new
NamedParameterJdbcTemplate(dataSource);
}
public int countOfActorsByFirstName(String firstName) {
String sql = "select count(*) from T_ACTOR where first_name = :first_name";
Map namedParameters = Collections.singletonMap("first_name", firstName);
return this.namedParameterJdbcTemplate.queryForInt(sql,
namedParameters);
}
31. 31
We have so far seen:
◦ How Spring’s JDBC framework offers an
excellent way to implement very low-level data
access code without having to spend too much
time writing tedious JDBC code.
◦ Convenience methods of the JdbcTemplate
class
◦ Flexible NameParameterJdbcTemplate style of
programming using parameters
◦ Examples of JdbcTemplate and
NameParameterJdbcTemplate
32.
33. The Spring Framework supports integration with
Hibernate, Java Persistence API (JPA), Java Data Objects
(JDO) and iBATIS SQL Maps for resource management, data
access object (DAO) implementations, and transaction
strategies.
Benefits of using the Spring Framework to create your ORM
DAOs
◦ Easier testing.
◦ Common data access exceptions.
◦ General resource management.
◦ Integrated transaction management.
34. In the beginning – Hibernate 2.x
Session s =
HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx;
try {
tx = sess.beginTransaction();
//do some work
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
sess.close();
}
35. Spring came with a really nice class
Session sess = SessionFactoryUtils.getSession
(getSessionFactory(), false);
sess.save(item);
36. Now Hibernate 3 and Spring 3
Session s =
getSessionFactory().getCurrentSession();
s.save(item);
37. Concrete DAO class
extend HibernateDaoSupport
Directly injecting a HibernateTemplate into
your DAO class
Directly injecting the
Hibernate SessionFactory into your DAO class
◦ Possible because of Hibernate 3
42. 42
We have so far seen:
◦ How Spring’s JDBC framework offers an
excellent way to integrate ORM Libraries
◦ How Spring Supports Transaction’s for ORM
Tool
◦ Hibernate Configuration’s and annotation
support and integration with Spring
◦ Examples of Hibernate Integration with Spring
43.
44. Why Spring Transaction
Transaction Manager
Programmatic Transaction Handling
Declarative Transaction
◦ XML
◦ @Transactional
45.
46. Uniform API
On and off server
Programmatic Transaction
Declarative Transaction
Propagation Behaviors
51. Native transaction managers
◦ JDBC: DataSourceTransactionManager
◦ Hibernate: HibernateTransactionManager
◦ TopLink: TopLinkTransactionManager
◦ JDO: JdoTransactionManager
◦ etc
Native strategies work in any environment
◦ but only against a single database!
no distributed transaction coordination
◦ leverage full power of underlying resource
isolation levels, savepoints, etc
52. public Object someServiceMethod() { return transactionTemplate.execute(new TransactionCallback() { // the code in this method executes in a transactional context
Using the TransactionTemplate.
Using
PlatformTransactionManager implementation
directly.
public Object someServiceMethod() {
return transactionTemplate.execute(new TransactionCallback() {
// the code in this method executes in a transactional context
public Object doInTransaction(TransactionStatus status) {
updateOperation1(); return resultOfUpdateOperation2();
}
});
}
53. DefaultTransactionDefinition def = newDefaultTransactionDefinition();
// explicitly setting the transaction name is something that can only be
done programmatically
def.setName("SomeTxName");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRE
D);
TransactionStatus status = txManager.getTransaction(def);
try {
// execute your business logic here
}
catch (MyException ex) {
txManager.rollback(status); throw ex;
}
txManager.commit(status);
54. <bean id="petStoreTarget"> ... </bean>
<bean id="petStore"
class="org.springframework.transaction.interceptor.TransactionProxy
FactoryBean">
<property name="transactionManager" ref="txManager"/>
<property name="target" ref="petStoreTarget"/>
<property name="transactionAttributes"> <props>
<prop key="insert*">PROPAGATION_REQUIRED,-
MyCheckedException
</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
Adding -MyCheckedException here specifies that if the method
throws MyCheckedException or any subclasses, the transaction will automatically
be rolled back. Multiple rollback rules can be specified here, comma-separated. A
- prefix forces rollback; a + prefix specifies commit.
57. ◦ MANDATORY
Support a current transaction, throw an exception if none exists.
◦ NESTED
Execute within a nested transaction if a current transaction exists,
behave like PROPAGATION_REQUIRED else.
◦ NEVER
Execute non-transactionally, throw an exception if a transaction
exists.
◦ NOT_SUPPORTED
Execute non-transactionally, suspend the current transaction if one
exists.
◦ REQUIRED
Support a current transaction, create a new one if none exists.
◦ REQUIRES_NEW
Create a new transaction, suspend the current transaction if one
exists.
◦ SUPPORTS
Support a current transaction, execute non-transactionally if none
exists.
58. 58
We have so far seen:
◦ Spring’s Transactions Benefits
◦ Spring Programmatic Transactions
◦ Spring Declaratives Transactions
◦ Spring Declaratives Transactions with AOP
◦ Spring Annotations for Transactions
◦ Spring Transactions Propagations Behavior