This document discusses simple JDBC usage with Spring 2.5. It introduces the speaker and covers topics including when plain JDBC is more appropriate than an ORM, new Spring 2.5 JDBC features like SimpleJdbcTemplate and SimpleJdbcCall, and examples of using these features for basic queries, updates, inserts, and stored procedures. Live code demonstrations are provided to illustrate working with SimpleJdbcTemplate, SimpleJdbcInsert, and SimpleJdbcCall.
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.
Validating JSON -- Percona Live 2021 presentationDave Stokes
JSON is a free form data exchange format which can cause problems when combined with a strictly typed relational database. Thanks to the folks at https://json-schema.org and the MySQL engineers at Oracle we can no specify required fields, type checks, and range checks.
Spring Data Requery is alternatives of Spring Data JPA
Requery is lightweight ORM for DBMS (MySQL, PostgreSQL, H2, SQLite, Oracle, SQL Server)
Spring Data Requery provide Query By Native Query, Query By Example and Query By Property like Spring Data JPA
Spring Data Requery is better performance than JPA
Validating JSON -- Percona Live 2021 presentationDave Stokes
JSON is a free form data exchange format which can cause problems when combined with a strictly typed relational database. Thanks to the folks at https://json-schema.org and the MySQL engineers at Oracle we can no specify required fields, type checks, and range checks.
Spring Data Requery is alternatives of Spring Data JPA
Requery is lightweight ORM for DBMS (MySQL, PostgreSQL, H2, SQLite, Oracle, SQL Server)
Spring Data Requery provide Query By Native Query, Query By Example and Query By Property like Spring Data JPA
Spring Data Requery is better performance than JPA
This session will provide a complete tour of using the Spring MVC framework to build Java Portlets. It will include an in-depth review of a sample portlet application developed using the latest features of Spring MVC, including Annotation-based Controllers. If you are writing Portlets and using Spring, this session is for you.
We'll begin by discussing the unique differences and challenges when developing Portlets instead of traditional Servlet webapps. Then we'll talk about the unique approach that Spring MVC takes towards Portlets that fully leverages the Portlet lifecycle, instead of masking it like many other frameworks. We'll take an extensive tour of a sample application so we can see all the unique pieces of the framework in action. Finally we'll conclude with discussion of the upcoming support for the Portlet 2.0 (JSR 286) specification that will be part of Spring 3.0.
The Spring Expression Language (SpEL for short) is a powerful expression language that supports querying and manipulating an object graph at runtime. The language syntax is similar to Unified EL but offers additional features, most notably method invocation and basic string templating functionality.
Introduction to Annotations.
What are Annotations➔ Annotations are structured information added to program source code➔ Annotations associated meta-information with definitions➔ They can be attached to any variable, method, expression, or another program element Like comments, they can be sprinkled throughout a program➔ Unlike comments, they have structure, thus making them easier to machine process.
www.AsteriskClub.org : Trucos muy interesantes imprescindibles para configurar y administrar un Asterisk para ahorrar tiempo y esfuerzo. Herramientas, técnicas y programación del Manager de Asterisk
Lecture 13 from the IAG0040 Java course in TTÜ.
See the accompanying source code written during the lectures: https://github.com/angryziber/java-course
Diseño Agil con TDD nos enseñará a:
* Escribir tests que aumenten la fiabilidad del código.
* Escribir tests de aceptación que nos ayudarán a centrarnos, específicamente, en el problema a resolver.
* Mejorar nuestros diseños para hacerlos más simples y flexibles.
* Escribir código fácil de mantener. Con TDD, los test son documentación viva y actualizada de nuestro código, la mejor documentación posible.
* Encajar TDD dentro del paradigma ágil y relacionarlo con otras técnicas como la integración continua.
JAVA CERTIFIED
http://www.lulu.com/content/multimedia/scjp-sun-certified-programmer-for-java-6-exam-310-065/7290203
Quieres certificarte en SCJP. y tu presupuesto es bajo y tienes cualidades de autodidacta lo mejor que puedes hacer es Googlear.. o mejor comprar esta libro Virtual.(SCJP Sun Certified Programmer) muy completo. si lo estudias a conciencia tendrias un %85 del examen.
Modelo Del Negocio con RUP y UML Parte 3.
Las tres publicaciones (parte 1, 2, 3 ) lo pueden descargar desde http://www.lulu.com/content/multimedia/modelo-de-negocio-con-rup-y-uml/8521887
Version de descarga http://www.lulu.com/content/e-book/instalacion-de-elastix/8274959
www.AsteriskClub.org: Manual Explicativo de Elastix (Asterisk) basado en Centos, lleva preinstalado Asterisk, FreePBX, y A2B, vTiger CRM, Hylafax, y un Modulo CallCenter, y otras soluciones adicionales.
http://www.lulu.com/content/e-book/instalacion-debian-asterisk-freepbx-a2billing/7540358
Manual practico de instalación de Asterisk, FreePBX, A2Billing en Linux (Debian). La idea principal es que cualquier persona sin experiencia pueda comenzar a instalar y utilizar asterisk, empezando con la instalación del sistema operativo y sus dependencias para luego instalar asterisk y administrarlo via web usando freePBX, Rutear llamadas facturando con A2Billing.
Para Descargar Libro ir al URL http://www.lulu.com/content/e-book/instalacion-debian-asterisk-freepbx-a2billing/7540358
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
1. Simple JDBC with
Spring 2.5
Thomas Risberg
SpringSource Inc.
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
2. Introduction
• Background - COBOL programmer, Oracle
DBA, J2EE developer, Spring developer,
SpringSource employee
• Committer on the Spring Framework
project since 2003, supporting the JDBC
and Data Access code
• Co-author of “Professional Java
Development with the Spring Framework”
from Wrox
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 2
3. Agenda
• JDBC development doesn’t have to be
difficult
• When is JDBC more appropriate than an
ORM solution
• Look at new Spring 2.5 JDBC features
• A few other 2.5 features that are handy for
data access development and testing
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 3
4. Yuck!!
public class JdbcDaoImpl {
public int getCustomerCount() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
int count = 0;
Properties properties = new Properties();
try {
properties.load(new FileInputStream("jdbc.properties"));
Using
} catch (IOException e) {
throw new MyDataAccessException(“I/O Error”, e);
}
try {
straight
Class.forName(properties.getProperty("driverClassName"));
conn = DriverManager.getConnection(properties.getProperty("url"), properties);
stmt = conn.createStatement();
rs = stmt.executeQuery("select count(*) from customers");
JDBC code
if (rs.next()) {
count = rs.getInt(1);
}
}
catch (ClassNotFoundException e) {
throw new MyDataAccessException(“JDBC Error”, e);
}
catch (SQLException se) {
throw new MyDataAccessException(“JDBC Error”, se);
}
finally {
if (rs != null) {
try {
rs.close();
}
catch (SQLException ignore) {}
}
if (stmt != null) {
try {
stmt.close();
}
catch (SQLException ignore) {}
}
if (conn != null) {
try {
conn.close();
}
catch (SQLException ignore) {}
}
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
} 4
return count;
}
}
5. Much better!
@Repository
public class SpringDaoImpl {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public int getCustomerCount() {
return jdbcTemplate.queryForInt("select count(*) from customers");
}
}
<context:property-placeholder location="classpath:jdbc.properties"/>
<context:annotation-config/>
<context:component-scan base-package="com.springsource.data.sample"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${db.driverClassName}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 5
6. Who does what?
Task Spring You
Connection Management √
SQL √
Statement Management √
ResultSet Management √
Row Data Retrieval √
Parameter Declaration √
Parameter Setting √
Transaction Management √
Exception Handling √
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 6
7. Plain JDBC vs. Spring JDBC
JDBC Spring
DriverManager / DataSource
DataSource
Statement / JdbcTemplate /
PreparedStatement / SimpleJdbcTemplate,
CallableStatement SimpleJdbcCall,
SimpleJdbcInsert
MappingSqlQuery /
StoredProcedure
ResultSet / RowSet POJOs / List of POJOs or
Maps / SqlRowSet
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 7
8. Exception Translation
SQLException is translated to a more expressive sub-class of DataAccessException like
DataIntegrityViolationException or CannotAcquireLockException. This is translation is
based on SQL Error codes forts and then SQL State codes. Translation is controlled by
entries in sql-error-codes.xml.
sql-error-codes.xml
<bean id="MySQL" class="org.springframework.jdbc.support.SQLErrorCodes">
<property name="badSqlGrammarCodes">
<value>1054,1064,1146</value>
</property>
<property name="dataAccessResourceFailureCodes">
<value>1</value>
</property>
<property name="dataIntegrityViolationCodes">
<value>1062</value>
</property>
<property name="cannotAcquireLockCodes">
<value>1205</value>
</property>
<property name="deadlockLoserCodes">
<value>1213</value>
</property>
</bean>
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 8
10. When should you use JDBC?
• Trivial domain model, few tables
• Complex queries reading and modifying
multiple tables
• Stored procedures, db specific data
types
• Bulk operations
• Tasks where you are not mapping
relational data to an object graph
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10
11. Mix JDBC and ORM
• It’s not an either or situation
• You can mix ORM access with JDBC
• Stored procedures are typically better
supported with JDBC
• ORM and JDBC share transaction
management - can participate in same
transaction
• Remember to flush ORM session/entity
manager before JDBC access
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 11
12. Simple Example
• Single Table (MySQL)
CREATE
TABLE customer
(
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50),
customer_number varchar(50),
birth_date date,
PRIMARY KEY USING BTREE (id)
)
ENGINE= InnoDB DEFAULT CHARSET= latin1
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 12
13. The Customer class
package com.springsource.data.sample.domain;
import java.util.Date;
public class Customer
{
private Long id;
private String name;
private String customerNumber;
private Date birthDate;
// getters and setters //
}
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 13
14. DAO/Repository Interface
package com.springsource.data.sample.repository;
import java.util.List;
import com.springsource.data.sample.domain.Customer;
public interface CustomerRepository {
void add(Customer customer);
Customer findById(Long id);
void save(Customer customer);
List<Customer> findAll();
}
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 14
15. Spring 2.5 and SimpleJdbc
• Spring 2.5 features for Simple JDBC:
– SimpleJdbcTemplate (named parameter support)
– SimpleJdbcInsert
– SimpleJdbcCall
– Annotation configuration
• @Repository, @Service, @Component
• @Autowired, @Qualifier
– JUnit 4 support
• @RunWith(SpringJUnit4ClassRunner.class)
• @ContextConfiguration
• @Transactional @Test
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 15
16. Simple Queries
Customer customer = simpleJdbcTemplate.queryForObject(
"select id, name, customer_number, birth_date from customer where id = ?",
ParameterizedBeanPropertyRowMapper.newInstance(Customer.class),
id);
List<Customer> customerList = simpleJdbcTemplate.query(
"select id, name, customer_number, birth_date from customer",
ParameterizedBeanPropertyRowMapper.newInstance(Customer.class));
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 16
17. Simple Updates
named parameters
simpleJdbcTemplate.update(
"update customer set name = :name, birth_date = :birth_date where id = :id",
new BeanPropertySqlParameterSource(customer));
source of values to match parameters
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 17
18. Passing in parameter values
• java.util.Map
– simple but doesn’t provide type info
• MapSqlParameterSource
– provides option of passing in SQL type
values.addValue("birth_date", customer.getBirthdate(), Types.DATE)
• BeanPropertySqlParameterSource
– automatic mapping of property values from a
JavaBean to parameters of same name
– provides option of specifying SQL type
values.registerSqlType("birth_date", Types.DATE)
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 18
19. Mapping results
• ParameterizedRowMapper
– provides for customized mapping from
results data to domain class
• ParameterizedBeanPropertyRowMapper
– automatic mapping from results data to a
JavaBean. Column names are mapped to
properties. (Use column aliases if names
don’t match)
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 19
20. Live Code
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 20
21. Insert data and access
generated keys
• Traditionally a bit tricky - need to use
PreparedStatementCreator and a
KeyHolder
• What if -
– you knew the name of the table
– the name and type of the columns
• Maybe the JDBC framework could
provide the rest ...
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 21
22. Database Metadata
customer table
column name
parameter type
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 22
23. SimpleJdbcInsert
private SimpleJdbcInsert insertCustomer;
...
this.insertCustomer = new SimpleJdbcInsert(dataSource)
.withTableName("customer")
.usingGeneratedKeyColumns("id");
Number newId =
insertCustomer.executeAndReturnKey(
new BeanPropertySqlParameterSource(customer));
customer.setId(newId.longValue());
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 23
24. SimpleJdbcInsert
• Simplifies insert operations
• Uses table metadata to provide
automatic column configuration
• Option to provide explicit configuration
• Supports auto generated keys in a
database independent fashion
• Supports batch inserts of arrays of Maps
or SqlParameters
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 24
25. Live Code
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 25
26. Stored Procedures
• Are they really that hard to use?
• What if -
– you knew the name of the procedure
– the name and type of the parameters
• Maybe the JDBC framework could
provide the rest ...
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 26
27. generate_customer_no
declaration
CREATE PROCEDURE generate_customer_no(
IN in_prefix varchar(10),
OUT out_customer_no varchar(50))
BEGIN
SELECT CONCAT(in_prefix, '.',
(RAND() * 10000000))
INTO out_customer_no;
END
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 27
28. Database Metadata
generate_customer_no
in or out
procedure name
column/parameter name SQL type
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 28
29. SimpleJdbcCall
generate_customer_no
private SimpleJdbcCall generateCustomerNumberCall;
...
this.generateCustomerNumberCall = new SimpleJdbcCall(dataSource)
.withProcedureName("generate_customer_no");
String customerNumber = generateCustomerNumberCall.executeObject(
String.class,
Collections.singletonMap("in_prefix", "XYZ"));
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 29
30. SimpleJdbcCall
DEBUG output
DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - JdbcCall call not compiled before execution - invoking compile
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataProviderFactory] - Using
org.springframework.jdbc.core.metadata.GenericCallMetaDataProvider
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataProvider] - Retrieving metadata for null/null/generate_customer_no
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataProvider] - Retrieved metadata: in_prefix 1 12 VARCHAR false
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataProvider] - Retrieved metadata: out_customer_no 4 12 VARCHAR
false
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataContext] - Added metadata in parameter for: in_prefix
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataContext] - Added metadata out parameter for: out_customer_no
DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - Compiled stored procedure. Call string is [{call
generate_customer_no(?, ?)}]
DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - SqlCall for procedure [generate_customer_no] compiled
DEBUG [org.springframework.jdbc.core.metadata.CallMetaDataContext] - Matching {in_prefix=XYZ} with
{out_customer_no=out_customer_no, in_prefix=in_prefix}
DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - The following parameters are used for call {call
generate_customer_no(?, ?)} with: {in_prefix=XYZ}
DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - 1: in_prefix SQL Type 12 Type Name null
org.springframework.jdbc.core.SqlParameter
DEBUG [org.springframework.jdbc.core.simple.SimpleJdbcCall] - 2: out_customer_no SQL Type 12 Type Name null
org.springframework.jdbc.core.SqlOutParameter
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Calling stored procedure [{call generate_customer_no(?, ?)}]
DEBUG [org.springframework.jdbc.core.StatementCreatorUtils] - Setting SQL statement parameter value: column index 1,
parameter value [XYZ], value class [java.lang.String], SQL type 12
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - CallableStatement.execute() returned 'false'
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - CallableStatement.getUpdateCount() returned 0
INFO [org.springframework.jdbc.core.JdbcTemplate] - Added default SqlReturnUpdateCount parameter named #update-count-1
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - CallableStatement.getUpdateCount() returned -1
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 30
31. SimpleJdbcCall
• Simplifies access to stored procedures
• Any database can be used with explicit
parameter configuration
• Supported databases provides automatic
parameter configuration:
– Apache Derby
– DB2
– MySQL
– Microsoft SQL Server
– Oracle
– Sybase
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 31
32. Live Code
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 32
33. Q&A
Questions?
thomas.risberg@springsource.com
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 33
34. Source Code
Customer.java
package com.springsource.data.sample.domain;
import java.util.Date;
public class Customer
{
private Long id;
private String name;
private String customerNumber;
private Date birthDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
(continued)
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 34
35. Source Code
Customer.java (continued)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
}
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 35
36. Source Code
SimpleCustomerRepository.java
package com.springsource.data.sample.repository;
import java.util.Collections;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Repository;
import com.springsource.data.sample.domain.Customer;
@Repository
public class SimpleCustomerRepository implements CustomerRepository {
private SimpleJdbcTemplate simpleJdbcTemplate;
private SimpleJdbcInsert insertCustomer;
private SimpleJdbcCall generateCustomerNumberCall;
(continued)
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 36
37. Source Code
SimpleCustomerRepository.java (continued)
@Autowired
public void init(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
this.insertCustomer = new SimpleJdbcInsert(dataSource)
.withTableName("customer")
.usingGeneratedKeyColumns("id");
this.generateCustomerNumberCall = new SimpleJdbcCall(dataSource)
.withProcedureName("generate_customer_no");
}
public void add(Customer customer) {
String customerNumber = generateCustomerNumberCall.executeObject(
String.class,
Collections.singletonMap("in_prefix", "XYZ"));
customer.setCustomerNumber(customerNumber);
Number newId =
insertCustomer.executeAndReturnKey(
new BeanPropertySqlParameterSource(customer));
customer.setId(newId.longValue());
}
(continued)
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 37
38. Source Code
SimpleCustomerRepository.java (continued)
public Customer findById(Long id) {
Customer customer = simpleJdbcTemplate.queryForObject(
"select id, name, customer_number, birth_date from customer where id = ?",
ParameterizedBeanPropertyRowMapper.newInstance(Customer.class),
id);
return customer;
}
public void save(Customer customer) {
simpleJdbcTemplate.update(
"update customer set name = :name, birth_date = :birthDate where id = :id",
new BeanPropertySqlParameterSource(customer));
}
public List<Customer> findAll() {
List<Customer> customerList = simpleJdbcTemplate.query(
"select id, name, customer_number, birth_date from customer",
ParameterizedBeanPropertyRowMapper.newInstance(Customer.class));
return customerList;
}
}
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 38
40. Source Code
CustomerRepository4Tests.java (continued)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class CustomerRepository4Tests {
@Autowired
private CustomerRepository customerRepository;
@Autowired
private DataSource dataSource;
@Before
public void onSetUpInTransaction() throws Exception {
// Load test data
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute("delete from customer");
jdbcTemplate.execute(
"insert into customer (id, customer_number, name, birth_date) " +
"values (1, 'Z.12345.67890', 'Bubba', '1990-02-03')");
jdbcTemplate.execute(
"insert into customer (id, customer_number, name, birth_date) " +
"values (2, 'Z.12345.98765', 'Mary', '1988-01-31')");
}
(continued)
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 40
41. Source Code
CustomerRepository4Tests.java (continued)
@Transactional @Test
public void testFindAll() {
List<Customer> l = customerRepository.findAll();
assertEquals("Wrong number of customers returned", 2, l.size());
}
@Transactional @Test
public void testFindById() {
Customer c = customerRepository.findById(2L);
assertNotNull("Customer not found", c);
}
@Transactional @Test
public void testAddCustomer() {
Customer c = new Customer();
c.setBirthDate(new Date(19829922L));
c.setName("Sven");
customerRepository.add(c);
assertNotNull("Customer id not assigned", c.getId());
assertTrue("Bad customer id", 3 <= c.getId());
assertNotNull("Customer number not assigned", c.getCustomerNumber());
}
(continued)
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 41
42. Source Code
CustomerRepository4Tests.java (continued)
@Transactional @Test
public void testUpdateCustomer() {
Customer c = customerRepository.findById(2L);
c.setBirthDate(new Date(19829933L));
customerRepository.save(c);
Customer c2 = customerRepository.findById(2L);
assertEquals("BirthDate not updated", 18000000L, c2.getBirthDate().getTime());
}
}
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 42