Spring Jdbc WS - Pennsylvania State University
Transcript of Spring Jdbc WS - Pennsylvania State University
![Page 1: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/1.jpg)
Java ProgrammingLanguages in Depth Series
Chair of Software Engineering
JDBCSpring Framework
Web Services
Marco PiccioniMay 31st 2007
![Page 2: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/2.jpg)
Java Programming: Spring Framework and JDBC 2
Java Data Base Connectivity
The Spring Framework: introduction
Spring and data access: JDBC support
Web Services
Spring web services support
What will we be talking about
![Page 3: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/3.jpg)
Java Programming: Spring Framework and JDBC 3
Java Data Base Connectivity
![Page 4: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/4.jpg)
Java Programming: Spring Framework and JDBC 4
General picture
JDBC ODBC BridgeDriver
RDBMS
JDBC
API
Java code
+ SQL JDBC Driver
![Page 5: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/5.jpg)
Java Programming: Spring Framework and JDBC 5
The basic service for managing a set of JDBC drivers
We need to load and create an instance of the driverand to register it with the DriverManager
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”)
How can this happen?
Connecting via a DriverManager object
![Page 6: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/6.jpg)
Java Programming: Spring Framework and JDBC 6
We need to get the connection object that will be usedto communicate with the database
Connection con = DriverManager.getConnection(“jdbc:odbc:MyDSN”, “MyLogin”, ”MyPassword”)
Java code just knows about DSN (Data Set Name)which is in turn mapped to the real database name For example in Windows you can use Control Panel
(ODBC Data Source) to set the mapping
Getting a connection
![Page 7: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/7.jpg)
Java Programming: Spring Framework and JDBC 7
A factory for connections to the physical data source
An object that implements the DataSource interfacewill typically be registered with a naming service basedon the Java Naming and Directory Interface (JNDI)API
Implemented by each driver vendor Basic -- produces a Connection object Connection pooling -- produces a Connection object
that will automatically participate in connectionpooling
Connecting via a DataSource object
![Page 8: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/8.jpg)
Java Programming: Spring Framework and JDBC 8
The Statement class is used to send SQL statementsto the DBMS
Statement stmt = con.createStatement();
A sample SQL query:
stmt.executeQuery(“SELECT * FROM CUSTOMERS;”);
If you need an update, insert or delete:
stmt.executeUpdate(“an SQL update, insert ordelete here”);
Statements and queries
![Page 9: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/9.jpg)
Java Programming: Spring Framework and JDBC 9
executeQuery() returns a ResultSet objectResultSet rs = stmt.executeQuery(“SELECT…”);
You can use the ResultSet object to iterate throughthe result The next() method moves the cursor to the next
row, and returns false when there are no more rows There are getter methods (getBoolean(), getLong(),
etc.) for retrieving column values from the currentrow
Handling the result set
![Page 10: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/10.jpg)
Java Programming: Spring Framework and JDBC 10
Remember to explicitely destroy the connection andthe statement objects after having done con.close()
stmt.close()
How can you be sure about that?
Cleaning up everything
![Page 11: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/11.jpg)
Java Programming: Spring Framework and JDBC 11
A JDBC sample
public String getPassword(String name) throwsApplicationException{String sql = "SELECT password FROM Customers WHEREid=‘" +name+“‘ ";String password = null;
Connection con = null; Statement s = null; ResultSet rs = null;
try { con = <get connection from DataSource>;s = con.createStatement();rs = s.executeQuery (sql);while (rs.next()) { password = rs.getString(1);}
rs. close(); s. close(); con.close(); }catch (SQLException ex) { throw newApplicationException ("Couldn't run query [" + sql +"]", ex); } return password; }
![Page 12: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/12.jpg)
Java Programming: Spring Framework and JDBC 12
A JDBC sample (improved)
public String getPassword(String name) throwsApplicationException{<as before…> rs. close(); s. close();} catch (SQLException ex) { throw newApplicationException ("Couldn't run query [" + sql +"]", ex); }
finally {try {
if (con != null) { con. close();}} catch (SQLException ex) { throw new
ApplicationException ("Failed to close connection",ex);}} //end finallyreturn password;}
![Page 13: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/13.jpg)
Java Programming: Spring Framework and JDBC 13
Across different DBMS Strings quoting may be different Code gets bloated with ugly string concatenations
String query = "Select * from Courses where " +
" id = \"" + id + "\"" +
" and name = \"" + name + "\"" +
" and year = " + year;
Statement issues
![Page 14: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/14.jpg)
Java Programming: Spring Framework and JDBC 14
Prepared statements (pre-compiled queries) are morereadable and the resulting code is more portable
Favour query optimization
String SQL = “select * from Courses where id = ? andname = ? and year = ? ";
PreparedStatement pstmt =connection.prepareStatement(SQL);
pstmt.setString(1,id);
pstmt.setString(2,name);
pstmt.setInt(3,year);pstmt.executeQuery();
Prepared statements
![Page 15: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/15.jpg)
Java Programming: Spring Framework and JDBC 15
The Spring Framework:introduction
![Page 16: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/16.jpg)
Java Programming: Spring Framework and JDBC 16
It addresses areas that other frameworks don’t Does not reinvent the wheel It is both comprehensive and modular Consistent and simple programming model (based on POJOs) Designed to help in writing code that is easy to unit test Effectively organizes middle tier objects Centralizes configuration A light weight alternative to EJB’s (most of the time) Eliminates Singleton proliferation Consistent framework for data access Applies good OO practices Open source project since February 2003 20 fully devoted developers, more than 1 million downloads
Yet another framework?
![Page 17: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/17.jpg)
Java Programming: Spring Framework and JDBC 17
The overall picture
Picture from http://static.springframework.org/spring/docs/2.0.x/reference/introduction.html
![Page 18: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/18.jpg)
Java Programming: Spring Framework and JDBC 18
A step by step introduction to the Spring Core
Inversion of Control/Dependancy Injection
Architectural model
Centralized configuration
What’s next?
![Page 19: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/19.jpg)
Java Programming: Spring Framework and JDBC 19
A deceivingly simple example
public class HelloWorld
{
public static void main(String[] aaargh)
{
System.out.println(”Hello again?!");
}
}
![Page 20: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/20.jpg)
Java Programming: Spring Framework and JDBC 20
What if we want to change the message? What if we want to output the message differently,
maybe to stderr instead of stdout, or enclosed inHTML tags rather than as plain text?
New requirements Our application should support a simple, flexible
mechanism for changing the message, and It should be simple to change the rendering
behavior.
Things happen to change…
![Page 21: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/21.jpg)
Java Programming: Spring Framework and JDBC 21
Which is the simplest way in which we can refactor thecode so that we can change the message withoutchanging the code? Using it as a command line argument
How to decouple the message handling in the code? Separating the component that renders the
message from the component that obtains themessage
Two little exercises
![Page 22: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/22.jpg)
Java Programming: Spring Framework and JDBC 22
A more flexible design
<<interface>>
MessageRenderer
+setMessageProvider()
+getMessageProvider()
+render()
StandardOutMessageRenderer
+setMessageProvider()
+getMessageProvider()
+render()
<<interface>>
MessageProvider
+getMessage()
HelloWorldMessageProvider
+getMessage()
![Page 23: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/23.jpg)
Java Programming: Spring Framework and JDBC 23
A decoupled Hello World
public class DecoupledHelloWorld
{
public static void main(String[] args)
{
MessageRenderer mr = new StandardOutMessageRenderer();
MessageProvider mp = new HelloWorldMessageProvider();
mr.setMessageProvider(mp);
mr.render();
}
}
![Page 24: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/24.jpg)
Java Programming: Spring Framework and JDBC 24
But we can do better…
public class DecoupledHelloWorldWithFactory
{
public static void main(String[] args)
{
MessageRenderer mr=MessageSupportFactory.getInstance().getMessageRenderer();
MessageProvider mp =MessageSupportFactory.getInstance().getMessageProvider();
mr.setMessageProvider(mp);
mr.render();
}
}
![Page 25: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/25.jpg)
Java Programming: Spring Framework and JDBC 25
A Factory snippet private MessageSupportFactory() {
bundle=ResourceBundle.getBundle("ch.ethz.inf.java.hello.msgConf");
StringrendererClass=bundle.getString("renderer.class");
StringproviderClass=bundle.getString("provider.class");
try {
renderer=(MessageRenderer)Class.forName(rendererClass).newInstance();
provider=(MessageProvider)Class.forName(providerClass).newInstance();
} catch (InstantiationException e) {
//exception handling code} catch (IllegalAccessException e) {
//exception handling code} catch (ClassNotFoundException e) {
//exception handling code} }
![Page 26: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/26.jpg)
Java Programming: Spring Framework and JDBC 26
We had to write lots of “glue” code
We still had to provide the implementation ofMessageRenderer with an instance of MessageProvidermanually
Flexibility comes at a price
![Page 27: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/27.jpg)
Java Programming: Spring Framework and JDBC 27
Here is where the Spring Framework comes into play
Provides lots of well written plumbing code
Sets the dependencies automatically
Hello Spring
![Page 28: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/28.jpg)
Java Programming: Spring Framework and JDBC 28
Let’s have a look at this public class XmlConfigHelloSpringDI { public static void main(String[] args) throws
Exception {
BeanFactory factory = getBeanFactory(); MessageRenderer mr =
(MessageRenderer)factory.getBean("renderer");
mr.render(); }
private static BeanFactory getBeanFactory() throwsException
{ XmlBeanFactory factory = new XmlBeanFactory(new
FileSystemResource("src/ch/ethz/inf/java/hello/msgConf.xml"));
return factory;
}}
![Page 29: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/29.jpg)
Java Programming: Spring Framework and JDBC 29
Sample Spring configuration file <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="renderer"
class=“ch.ethz.inf.java.hello.StandardOutMessageRenderer">
<property name="messageProvider">
<ref local="provider"/>
</property>
</bean>
<bean id="provider"
class="ch.ethz.inf.java.hello.HelloWorldMessageProvider"/>
</bean></beans>
![Page 30: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/30.jpg)
Java Programming: Spring Framework and JDBC 30
Dependency lookup Dependency pull
Dependency injection (DI) Setter DI Constructor DI
Kinds of dependency handling
![Page 31: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/31.jpg)
Java Programming: Spring Framework and JDBC 31
Your application interacts with the Spring DIcontainer via the BeanFactory interface
All the BeanFactory implementations act ascentralized registers that provide beans by name
The Spring BeanFactory interface
![Page 32: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/32.jpg)
Java Programming: Spring Framework and JDBC 32
Provides more services with respect to theBeanFactory interface Internationalization Handles many configuration files Publishes events Handles more in depth beans lifecycle …
The Spring ApplicationContext interface
![Page 33: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/33.jpg)
Java Programming: Spring Framework and JDBC 33
HelloWorldMessageProvider returns the same hard-coded message for each call of getMessage()
In the Spring configuration file, I can easily create aconfigurable MessageProvider that allows the messageto be defined externally
Externalizing the message
![Page 34: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/34.jpg)
Java Programming: Spring Framework and JDBC 34
public class ConfigurableMessageProviderimplements MessageProvider
{
private String message;
private ConfigurableMessageProvider(String
message)
{
this.message=message;
}
public String getMessage() {
return message;
}
}
A configurable message provider
![Page 35: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/35.jpg)
Java Programming: Spring Framework and JDBC 35
…<bean id="provider"class="ch.ethz.inf.java.hello.ConfigurableMessageProvider">
<constructor-arg>
<value>This is a configurablemessage</value>
</constructor-arg>
</bean>
…
Constructor injection sample
![Page 36: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/36.jpg)
Java Programming: Spring Framework and JDBC 36
The framework provides many PropertyEditorimplementations to convert the string values in theconfiguration file into:
URL’s, Locales, file paths,…
You can also set references and in particular handlecollections
Configuring values and references
![Page 37: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/37.jpg)
Java Programming: Spring Framework and JDBC 37
…<bean id=“sportsman" class=“ch.ethz.inf.java.injection.Sportsman">
<property name="sponsor"><ref local="aSponsor"/>
</property><property name=“sportEvents">
<map><entry key="Olympiads 2000">
<value>100 mt</value></entry><entry key="Olympiads 2004">
<value>200 mt</value></entry>
</map></property>
</bean><bean id="aSponsor"
class="ch.ethz.inf.java.injection.TechnicalSponsor"><property name="name">
<value>Adidas</value></property>
</bean>…
Sample reference configuration
![Page 38: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/38.jpg)
Java Programming: Spring Framework and JDBC 38
Dependence on the singleton class is hard coded inmany other classes
Singletons are interface-unfriendly Every singleton must handle its own configuration
(private constructor…) Testing with mock objects is more difficult It’s difficult to manage all singletons configuration in a
centralized and consistent way No inheritance (no overriding of static methods…)
Singleton issues
![Page 39: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/39.jpg)
Java Programming: Spring Framework and JDBC 39
…<bean id=”nonSingleton” class=”pickapkg.aClass”
singleton=”false”/>
…
As a default the framework provides singletons
The Spring solution
![Page 40: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/40.jpg)
Java Programming: Spring Framework and JDBC 40
When yes: Shared objects with no state Shared objects with read-only state Shared objects with shared state (use synchronization)
When there are only a few writings When many objects are created When creation is expensive Synchronization granularity should be high
Singletons in multithreaded environments
![Page 41: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/41.jpg)
Java Programming: Spring Framework and JDBC 41
When no:
Shared objects with many writable attributes
Objects with private state (not intended to beconceptually shared)
Singletons in multithreaded environments (2)
![Page 42: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/42.jpg)
Java Programming: Spring Framework and JDBC 42
Spring and data access:JDBC support
![Page 43: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/43.jpg)
Java Programming: Spring Framework and JDBC 43
A JDBC sample (improved)
public String getPassword(String name) throwsApplicationException{<as before…> rs. close(); s. close();} catch (SQLException ex) { throw newApplicationException ("Couldn't run query [" + sql +"]", ex); }
finally {try {
if (con != null) { con. close();}} catch (SQLException ex) { throw new
ApplicationException ("Failed to close connection",ex);}} //end finallyreturn password;}
![Page 44: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/44.jpg)
Java Programming: Spring Framework and JDBC 44
JDBC is a good, but quite low level API
It requires lots of effort on the developer side towrite and maintain glue code Loading and registering driver Handling connections Handling exceptions (JDBC API provides only a few
exceptions) Handling CRUD operations in a standard way
What’s wrong with JDBC?
![Page 45: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/45.jpg)
Java Programming: Spring Framework and JDBC 45
Spring provides a wealth of useful runtime exceptions: DataAccessResourceFailureException CleanupFailureDataAccessException InvalidDataAccessApiUsageException TypeMismatchDataAccessException InvalidDataAccessResourceUsageException DataRetrievalFailureException IncorrectUpdateSemanticDataAccessException DataIntegrityViolationException DeadlockLoserDataAccessException OptimisticLockingFailureException UnCategorizedDataAccessException …
Spring and data exceptions
![Page 46: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/46.jpg)
Java Programming: Spring Framework and JDBC 46
Checked exceptions are overused in Java
Spring will not force you to catch any exceptionfrom which you are unlikely to be able torecover
All Spring data exceptions are “unchecked”
Quiz: can we try-catch a runtime exception?
Spring and data exceptions (2)
![Page 47: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/47.jpg)
Java Programming: Spring Framework and JDBC 47
Spring provides a default implementation of theSQLExceptionTranslator interface, which takes care oftranslating the generic SQL error codes into runtimeSpring JDBC exceptions
You can even handle specific error codes by extendingSQLErrorCodeSQLExceptionTranslator and overriding
DataAccessException customTranslate (Stringtask, String sql, SQLException sqlex)
Spring and data exceptions (3)
![Page 48: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/48.jpg)
Java Programming: Spring Framework and JDBC 48
Handles JDBC core workflow
It is configurable with a javax.sql.DataSource andpublishes various methods to query and update data
Intercepts JDBC exceptions translating them
A developer has to implement some callback interfaces PreparedStatementSetter PreparedStatementCallback RowCallbackHandler RowMapper
Class JdbcTemplate
![Page 49: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/49.jpg)
Java Programming: Spring Framework and JDBC 49
List query(String query,PreparedStatementSetter pss,RowCallbackHandler rch)
int update(String updateQuery,PreparedStatementSetter pss)
JdbcTemplate: useful methods
![Page 50: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/50.jpg)
Java Programming: Spring Framework and JDBC 50
…JdbcTemplate jdbcTemplate = newJdbcTemplate(dataSource);ObjectRowMapper rowMapper = newUserRowMapper();List allUsers =jdbcTemplate.query("select * fromuser", newRowMapperResultReader(rowMapper,10));
…
JdbcTemplate: sample code
![Page 51: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/51.jpg)
Java Programming: Spring Framework and JDBC 51
…List userResults =jdbcTemplate.query("select * fromuser where id=?", new Object[] {id},new RowMapperResultReader(rowMapper,1));User user = (User)DataAccessUtils.uniqueResult(userResults);
…
JdbcTemplate: sample code (2)
![Page 52: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/52.jpg)
Java Programming: Spring Framework and JDBC 52
Web Services
![Page 53: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/53.jpg)
Java Programming: Spring Framework and JDBC 53
Web Services basics
A software system designed to support interoperablemachine to machine interaction over a network (W3C)
Self-contained and self-describing. Its interface isdescribed in WSDL
Clients and servers (endpoints) communicate via XMLmessages that follow the SOAP standard
Provides an API accessible over a network and executedon a remote system hosting the requested services
![Page 54: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/54.jpg)
Java Programming: Spring Framework and JDBC 54
Core specifications: SOAP
Service Oriented Architecture Protocol (former SimpleObject Access Protocol)
XML-based communication protocol
Has bindings to underlying protocols as HTTP,HTTPS, SMTP, XMPP
Message-wrapping format
Platform and language independent
![Page 55: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/55.jpg)
Java Programming: Spring Framework and JDBC 55
Core specifications: WSDL
Web Services Description Language
An XML format used to describe web servicesinterfaces and protocol bindings details in a platformindependent fashion
Also used for configuration and for generating clientand server code
Heavily backed by Microsoft (uses it for .NET)
![Page 56: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/56.jpg)
Java Programming: Spring Framework and JDBC 56
Core specifications: UDDI
Universal Description, Discovery and Integration A platform-independent, XML-based registry for
businesses to list themselves on the internet Each business can publish a service listing
An UDDI business registration is composed by: White Pages (address, contact and known identifiers) Yellow Pages (industrial categorizations) Green Pages (technical info about exposed services)
It is designed to be interrogated by SOAP messagesand to provide access to WSDL documents describingthe protocol bindings and message formats required tointeract with the web services listed in its directory
![Page 57: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/57.jpg)
Java Programming: Spring Framework and JDBC 57Picture from http://en.wikipedia.org/wiki/Web_services
![Page 58: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/58.jpg)
Java Programming: Spring Framework and JDBC 58
Styles of use
RPC (Remote procedure calls) Present a distributed function call interface Tightly coupled to language-specific function
SOA (Service Oriented Architecture) A message is the basic unit of communication Focus is on WSDL contract
RESTful (REpresentational State Transfer) Constrain the interface to a set of standard
operations Focus is on interacting with stateful resources
![Page 59: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/59.jpg)
Java Programming: Spring Framework and JDBC 59
A Java RPC-style implementation
JAX-RPC (Java API for XML-based Remote ProcedureCalls) provides a standard way for accessing andexposing RPC-style SOAP web services.
JAX-RPC 2.0 has been renamed to JAX-WS 2.0 (JavaAPI for XML Web Services)
The most popular JAX-RPC flavor is Apache Axis, a fullyJAX-RPC-compliant SOAP stack
![Page 60: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/60.jpg)
Java Programming: Spring Framework and JDBC 60
How JAX-WS works
A Java programs invokes a method on a stub (localobject representing the remote service)
The stub invokes routines in the JAX-WS RuntimeSystem
The JAX-WS Runtime System converts the remotemethod invocation into a SOAP message
the JAX-WS Runtime System transmits the messageas an HTTP request
Therefore the web service can be implemented on theserver side as a servlet or EJB container
![Page 61: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/61.jpg)
Java Programming: Spring Framework and JDBC 61
Web Services: assessment
Provide interoperability between different webapplications running on different platforms
Represent a possible solution for remoting
Adopt a specific tradeoff, namely interoperability andextensibility over ease-of-use and performance
RMI/EJB or Hessian/Burlap are better for plain Java toJava communication
![Page 62: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/62.jpg)
Java Programming: Spring Framework and JDBC 62
Spring Web Services support
![Page 63: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/63.jpg)
Java Programming: Spring Framework and JDBC 63
Spring and Web Services
Spring Web Services is a separate Spring subproject RC1 released on 22/5/2007
Main features: Contract-First development Loose coupling between contract and implementation XML API support (DOM, SAX, StAX, JDOM, dom4j,
XOM,…) Powerful mappings for distributing incoming XML
requests to objects based on message payload, SOAPAction header, XPath expressions
Flexible XML marshalling (support for JAXB 1 &2,Castor, XMLBeans, JiBX, XStream
Support for security (sign, encrypt, decrypt andauthenticate against SOAP messages)
![Page 64: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/64.jpg)
Java Programming: Spring Framework and JDBC 64
Contract-First Web Services
Contract-Last approach Write (Java) code first (interfaces) , and let the
Web Service contract (WSDL) be generated fromthat
Contract-First approach Write contract (WSDL) first, and use the language
(Java) to implement that contract
![Page 65: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/65.jpg)
Java Programming: Spring Framework and JDBC 65
Issues with Contract-Last development
Object/XML impedance mismatch
Fragility
Performance
Reusability
Versioning
![Page 66: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/66.jpg)
Java Programming: Spring Framework and JDBC 66
Object/XML impedance mismatch
XML (and XSD) are hierarchical, OO languages aremodeled by graphs
XSD extensions are not like inheritance E.g. a XSD restriction that uses a regular expression
is lost
Unportable types e.g. java.util.TreeMap, time and dates
Cyclic graphs A refers to B that refers to A
![Page 67: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/67.jpg)
Java Programming: Spring Framework and JDBC 67
Fragility and Performance
Not all SOAP stacks generate the same web servicecontract from a Java contract
By automatically transforming Java into XML, there isno guarantee on what is sent over the wire(dependencies can be very deep and unwanted)
Using contract-first you can choose what informationhas to be sent
![Page 68: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/68.jpg)
Java Programming: Spring Framework and JDBC 68
Reusability and Versioning
Defining your schema in a separate file you can reuse itin different scenarios
Starting from Java, when a contract evolves you have nochoice but to assign a different name to your interface.The old contract must be kept around for clients thatneed the older version
Starting from contracts, you can implement the old andthe new version of the contract in one class using XSLTfor conversions
![Page 69: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/69.jpg)
Java Programming: Spring Framework and JDBC 69
How to write a contract-first web service
See the tutorial at:
h t t p : / / s t a t i c . s p r i n g f r a m e w o r k . o r g / s p r i n g -ws/site/reference/html/tutorial.html
![Page 70: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/70.jpg)
Java Programming: Spring Framework and JDBC 70
References
Rob Harrop, Jan Machacek: Pro Spring. Apress 2005
Rod Johnson: Expert One-on-One J2EE Developmentwithout EJB. Wrox Press, 2004
Rod Johnson: Expert One-on-One J2EE Design andDevelopment. Wrox Press, 2001
Craig Walls, Ryan Breidenbach: Spring in ActionManning 2005
![Page 71: Spring Jdbc WS - Pennsylvania State University](https://reader031.fdocuments.us/reader031/viewer/2022012514/618ddb38991ef773e34db3c0/html5/thumbnails/71.jpg)
Java Programming: Spring Framework and JDBC 71
More references
http://www.springframework.org http://static.springframework.org/spring-ws/site/ http://www.w3.org/TR/ws-arch http://ws.apache.org/axis http://www.w3schools.com/xml/default.asp http://www.w3schools.com/schema/default.asp http://www.w3schools.com/soap/default.asp http://www.w3schools.com/wsdl/default.asp http://www.soapui.org/