SlideShare a Scribd company logo
1 of 74
Download to read offline
Spring Framework - Data Access




                SPRING FRAMEWORK 3.0
Dmitry Noskov   Data Access
Spring Data Access
   DAO support
   transaction management
   JDBC

   not included
     ORM
     marshalling XML




                        Spring Framework - Data Access   Dmitry Noskov
DAO support
jdbc namespace
Spring data access exceptions




              Spring Framework - Data Access   Dmitry Noskov
JDBC namespace
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xsi:schemaLocation="
           http://www.springframework.org/schema/   beans
           http://www.springframework.org/schema/   beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/   jdbc
           http://www.springframework.org/schema/   jdbc/spring-jdbc-3.0.xsd">



</beans>




                                 Spring Framework - Data Access   Dmitry Noskov
Embedded database

<jdbc:embedded-database id="dataSource" type="HSQL|H2|Derby">
  <jdbc:script location="classpath:db-schema.sql"/>
  <jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>



<bean class="org.exhanger.repository.jdbc.AccountJdbcRepository">
  <property name="dataSource" ref="dataSource"/>
</bean>




                       Spring Framework - Data Access   Dmitry Noskov
Populate other DataSource

<bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource">
  <property name="URL" value="${jdbc.url}"/>
  <property name="user" value="${jdbc.user}"/>
  <property name="password" value="${jdbc.password}"/>
</bean>


<jdbc:initialize-database data-source="dataSource" >
  <jdbc:script location="classpath:db-schema.sql"/>
  <jdbc:script location="classpath:test-data.sql"/>
</jdbc:initialize-database>




                       Spring Framework - Data Access   Dmitry Noskov
Problem of handling exceptions
   exceptions
     checked
     unchecked

   SQLException
     technology-specific
     depends on DBMS

     couple the DAO and API




                     Spring Framework - Data Access   Dmitry Noskov
Spring DataAccessException’s
   unchecked
   hide data access technology
     JDBC
     Hibernate

     etc.

   hide DBMS error codes




                    Spring Framework - Data Access   Dmitry Noskov
DataAccessException hierarchy
                                  RuntimeException



                                DataAccessException

    CleanupFailure                                                 DataIntegrity
  DataAccessException                                            ViolationException


          OptimisticLocking                               DeadlockLoser
          FailureException                              DataAccessException


                DataAccessResource
                                                       more…
                 FailureException


                              Spring Framework - Data Access   Dmitry Noskov
@Repository
@Repository
public class AccountJdbcRepository implements AccountRepository {


    @Autowired
    private DataSource dataSource;


    private JdbcTemplate jdbcTemplate;


    @Autowired
    public AccountJdbcRepository(DataSource dataSource) {
        super
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
}


                           Spring Framework - Data Access   Dmitry Noskov
Transaction management
Overview
Transaction models
Spring PlatformTransactionManager’s




              Spring Framework - Data Access   Dmitry Noskov
Unit of work
public Long process(Account account, Order o) {
    String owner = o.getOwner();
    String from = o.getFrom();
    String to = o.getTo();


    accountService.reduceBalance(account, to, o.getValue() * o.getRate());
    accountService.increaseBalance(account, from, o.getValue());


    accountService.reduceBalance(owner, from, o.getValue());
    accountService.increaseBalance(owner, to, o.getValue() * o.getRate());


    orderService.completeOrder(order.getId());


    return auditService.createRecord(account, o);
}



                             Spring Framework - Data Access   Dmitry Noskov
ACID principles
   atomicity
       "all or nothing" rule for unit of work
   consistency
       only consistent data will be saved
   isolation
       isolating transactions for each other
   durability
       commited changes are permanent


                          Spring Framework - Data Access   Dmitry Noskov
Transaction models
   local
     work across single transactional resource
     resource-specific

     easier to use

   global
       work across multiple transactional resources




                         Spring Framework - Data Access   Dmitry Noskov
Local transactions
   can be managed by DBMS, etc.
   depends on connection




                   Spring Framework - Data Access   Dmitry Noskov
Classic database transaction
public class AccountJdbcRepository implements AccountRepository {
  private DataSource dataSource;

    public void modifyAccount(Account account) {
      String sql = "...";
      Connection conn = null;

      try {
        conn = dataSource.getConnection();
        conn.setAutoCommit(false);
        PreparedStatement ps = conn.prepareStatement(sql);
        s.executeUpdate();
        conn.commit();
      } catch (SQLException e) {
        conn.rollback();
      }
}


                             Spring Framework - Data Access   Dmitry Noskov
Problems with local transactions
   connection management code is error-prone
   transaction demarcation belongs at the service
    layer
     multiple data access methods may be called within a
      transaction
     connection must be managed at a higher level




                      Spring Framework - Data Access   Dmitry Noskov
Spring transaction management
   declarative
     XML
     annotations

   programmatic




                    Spring Framework - Data Access   Dmitry Noskov
Namespace

<beans xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans/
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">


</beans>




                              Spring Framework - Data Access   Dmitry Noskov
Basic configuration
<beans>


  <tx:annotation-driven transaction-manager="transactionManager"
                            mode="proxy|aspectj"
                            order="0" <!-- Ordered.LOWEST_PRECEDENCE -->
                            proxy-target-class="false"/>


  <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
  </bean>


  <!-- <tx:jta-transaction-manager/> -->
</beans>



                                Spring Framework - Data Access   Dmitry Noskov
PlatformTransactionManager

                                 PlatformTransactionManager




DataSourceTransactionManager       JtaTransactionManager               HibernateTransactionManager




                                       WebLogicJtaTransactionManager




                                      WebSphereUowTransactionManager




                               Spring Framework - Data Access     Dmitry Noskov
@Transactional
@Transactional
public class AccountServiceImpl implements AccountService {


    @Transactional
    public Account getAccount(Long accountId) {
        return repository.getAccount(accountId);
    }


    @Transactional
    public Long createAccount(Account account) {
        return repository.createAccount(account);
    }
}


                            Spring Framework - Data Access   Dmitry Noskov
How it works


               Spring Framework - Data Access   Dmitry Noskov
Transactional attributes
   propagation
   isolation
   rollback rules
   read-only
   timeout




                     Spring Framework - Data Access   Dmitry Noskov
Transaction propagation(1)
   REQUIRED
       support a current transaction, create a new one if none exists
    @Transactional(propagation = Propagation.REQUIRED)
    public Long process(Account account, Order order){}

   REQUIRED_NEW
       create a new transaction, suspend the current if one exists
    @Transactional(propagation = Propagation.REQUIRED_NEW)
    public Long process(Account account, Order order){}

   NESTED
       single physical transaction with multiple savepoints


                              Spring Framework - Data Access   Dmitry Noskov
REQUIRED




           Spring Framework - Data Access   Dmitry Noskov
REQUIRED_NEW




         Spring Framework - Data Access   Dmitry Noskov
Transaction propagation(2)
   SUPPORTS
       support a current transaction, or execute non-transactionally
   MANDATORY
       support a current transaction, throw an exception if none exists
   NOT_SUPPORTED
       execute non-transactionally, suspend the current transaction
   NEVER
       execute non-transactionally, throw an exception if a transaction exists



                              Spring Framework - Data Access   Dmitry Noskov
Isolation levels
   levels
     READ_UNCOMMITED
     READ_COMMITED

     REPEATABLE_READ

     SERIALIZABLE

   DBMS
     have differences in implementation
     may not support something



                       Spring Framework - Data Access   Dmitry Noskov
READ_UNCOMMITED
   lowest isolation level
   dirty reads are allowed
   example
    @Transactional(isolation = Isolation.READ_UNCOMMITTED)
    public Order getOrder(Long orderId) {
        return repository.getOrder(orderId);
    }




                           Spring Framework - Data Access   Dmitry Noskov
READ_COMMITED
   default strategy for most DBMSs
   only commited data can be accessed
   example
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public Order getOrder(Long orderId) {
        return repository.getOrder(orderId);
    }




                           Spring Framework - Data Access   Dmitry Noskov
Highest isolation levels
   REPEATABLE_READ
       prevents non-repeatable reads
   SERIALIZABLE
       prevents phantom reads




                        Spring Framework - Data Access   Dmitry Noskov
Rollback rules
@Service
public class AccountServiceImpl implements AccountService {


    @Transactional(rollbackFor = CheckedException.class)
    public Long createAccount(Account account) {
        return repository.createAccount(account);
    }


    @Transactional(noRollbackFor = SendNotificationException.class)
    public void modifyAccount(Account account) {
        repository.modifyAccount(account);
    }
}


                            Spring Framework - Data Access   Dmitry Noskov
Read-only transactions
   optimize resource for read-only access
   example
    @Transactional(readOnly = true)
    public Account getAccount(Long accountId) {
        return repository.getAccount(accountId);
    }




                           Spring Framework - Data Access   Dmitry Noskov
Trsnsaction timeout
   example
    @Transactional(timeout = 60)
    public List<Order> getActiveOrders(String from, String to) {
    }




                         Spring Framework - Data Access   Dmitry Noskov
Multiple transaction managers
<tx:annotation-driven/>
<bean id="transactionManager1" class="...">
  <qualifier value="txManager1"/>
</bean>
<bean id="transactionManager2" class="...">
  <qualifier value="txManager2"/>
</bean>


@Transactional(value = "txManager1")
public BigDecimal method1 (Order order) {}


@Transactional(value = "txManager2")
public Account merge(Account account) {}



                          Spring Framework - Data Access   Dmitry Noskov
Custom shortcut annotations
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional("txManager1")
public @interface OrderTx {}

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional("txManager2")
public @interface AccountTx {}

Using:
@OrderTx
public BigDecimal method1 (Order order) {}

@AccountTx
public Account merge(Account account) {}



                           Spring Framework - Data Access   Dmitry Noskov
Programmatic transactions
   TransactionTemplate
   PlatformTransactionManager




                    Spring Framework - Data Access   Dmitry Noskov
TransactionTemplate(1)
public class AccountServiceImpl implements AccountService {
    private final TransactionTemplate template;


    private AccountServiceImpl(PlatformTransactionManager manager) {
        template = new TransactionTemplate(manager);
    }


    public Object method1(final Object obj) {
        return template.execute(new TransactionCallback<Object>() {
          public Object doInTransaction(TransactionStatus status) {
              return operation(obj);
          }
    });
}

                               Spring Framework - Data Access   Dmitry Noskov
TransactionTemplate(2)
public class AccountServiceImpl implements AccountService {
 private final TransactionTemplate template;


 private AccountServiceImpl(PlatformTransactionManager manager) {
      template = new TransactionTemplate(manager);
 }


 public void method2(final Object obj) {
     template.execute(new TransactionCallbackWithoutResult() {
      protected void doInTransactionWithoutResult(TransactionStatus st){
          operation(obj);
      }
     });
 }

                            Spring Framework - Data Access   Dmitry Noskov
TransactionTemplate(3)
public class AccountServiceImpl implements AccountService {
    private final TransactionTemplate template;


    public void method3(final Object obj) {
     template.execute(new TransactionCallbackWithoutResult() {
         protected void doInTransactionWithoutResult(TransactionStatus s){
             try {
                 operation(obj);
             } catch (RuntimeException e) {
                 status.setRollbackOnly();
             }
         }
    );
}


                                   Spring Framework - Data Access   Dmitry Noskov
PlatformTransactionManager
public interface PlatformTransactionManager {
    /** Return a currently active transaction or create a new one,
        according to the specified propagation behavior. */
    TransactionStatus getTransaction(TransactionDefinition definition);


    /** Commit the given transaction, with regard to its status. If
    the transaction has been marked rollback-only programmatically,
    perform a rollback. */
    void commit(TransactionStatus status);


    /** Perform a rollback of the given transaction. */
    void rollback(TransactionStatus status);
}


                             Spring Framework - Data Access   Dmitry Noskov
XML-based
<tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
    <tx:method name="get*" read-only="true"/>
    <tx:method name="*" propagation="REQUIRED"
               isolation="READ_COMMITTED"
               rollback-for="java.lang.Throwable" />
  </tx:attributes>
</tx:advice>


<aop:config>
  <aop:pointcut id="txOperation"
       expression="execution(* org.training.api..*ServiceImpl.*(..))"/>
  <aop:advisor pointcut-ref="txOperation"
                advice-ref="txAdvice"
                order="" />
</aop:config>




                              Spring Framework - Data Access   Dmitry Noskov
Spring JDBC




        Spring Framework - Data Access   Dmitry Noskov
Strong JDBC
public List<Account> getAccountsByType(Long type) {
  List<Account> accounts = new ArrayList<Account>();
  Connection connection = null;
  String sql = "select account_id, account_owner from account";
  try {
    connection = dataSource.getConnection();
    PreparedStatement ps = connection.prepareStatement(sql);
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
      accounts.add(new Account(rs.getLong(1), rs.getString(2)));
    }
  } catch (SQLException e) {/*handle exception*/}
  finally {
    try { connection.close();} catch (SQLException e) {/*handle*/}
  }
  return accounts;
}


                           Spring Framework - Data Access   Dmitry Noskov
Target code
public List<Account> getAccountsByType(Long type) {
  List<Account> accounts = new ArrayList<Account>();
  Connection connection = null;
  String sql = "select account_id, account_owner from account";
  try {
    connection = dataSource.getConnection();
    PreparedStatement ps = connection.prepareStatement(sql);
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
      accounts.add(new Account(rs.getLong(1), rs.getString(2)));
    }
  } catch (SQLException e) {/*handle exception*/}
  finally {
    try { connection.close();} catch (SQLException e) {/*handle*/}
  }
  return accounts;
}


                           Spring Framework - Data Access   Dmitry Noskov
Who does what
Action                                       Spring                    You
Define connection parameters                                                    X
Connection management                                   X
SQL                                                                             X
Statement management                                    X
ResultSet management                                    X
Row Data Retrieval                                                              X
Exception handling                                      X
Handle transactions                                     X




                               Spring Framework - Data Access   Dmitry Noskov
Spring JDBC abstractions
JdbcTemplate
NamedParameterJdbcTemplate
SimpleJdbcTemplate
SimpleJdbcInsert and SimpleJdbcCall




              Spring Framework - Data Access   Dmitry Noskov
JdbcTemplate




        Spring Framework - Data Access   Dmitry Noskov
Creating the JdbcTemplate

@Repository
public class AccountJdbcRepository implements AccountRepository {


    private JdbcTemplate jdbcTemplate;


    public AccountJdbcRepository(DataSource dataSource) {
        super();
        jdbcTemplate = new JdbcTemplate(dataSource);
    }
}




                             Spring Framework - Data Access   Dmitry Noskov
Simple types

int intCount =
    jdbcTemplate.queryForInt("select count(*) from accounts");


int longCount =
    jdbcTemplate.queryForLong (
        "select count(*) from accounts
         where account_owner like ?", "name");


String name =
    jdbcTemplate.queryForObject(
        "select account_owner from accounts
         where account_id = ?", new Object[]{10}, String.class);



                         Spring Framework - Data Access   Dmitry Noskov
Generic maps

public Map<String, Object> getAccount(Long accountId) {
    String sql = "select * from accounts where account_id = ?";
    return jdbcTemplate.queryForMap(sql, accountId);
}



public List<Map<String, Object>> getAccounts() {
    return jdbcTemplate.queryForList("select * from accounts");
}




                         Spring Framework - Data Access   Dmitry Noskov
Domain object(1)

Account account =
 jdbcTemplate.queryForObject(
    "select account_id, account_owner from accounts
     where account_id = ?",
        new Object[]{11},
        new RowMapper<Account>(){
          public Account mapRow(ResultSet rs, int rowNum){
              Account account = new Account();
              account.setId(rs.getLong("account_id"));
              account.setOwner (rs.getString("account_owner"));
              return account;
           }
        });

                            Spring Framework - Data Access   Dmitry Noskov
Domain object(2)
List<Account> accounts =
 jdbcTemplate.query(
    "select account_id, account_name from m_accounts
     where account_id = ?",
     new Object[]{11},
     new RowMapper<Account>(){
       public Account mapRow(ResultSet rs, int rowNum) {
           Account account = new Account();
           account.setId(rs.getLong("account_id"));
           account.setName(rs.getString("account_name"));


           return account;
       }
     });

                             Spring Framework - Data Access   Dmitry Noskov
Callback handler
public void writeAccountsToFile(File f) {
    jdbcTemplate.query("select * from account", new FileWriter(f));
}


public class FileWriter implements RowCallbackHandler {
    public FileWriter(File file) {
        super();
    }


    public void processRow(ResultSet rs) throws SQLException {
        //write result set to file
    }
}


                            Spring Framework - Data Access   Dmitry Noskov
ResultSet extractor
public Account getAccount(long accountId) {
    String sql = "select * from accounts where account_id = ?";
    return jdbcTemplate.query(sql,
                                   new Object[]{accountId},
                                   new Extractor());
}


public class Extractor implements ResultSetExtractor<Account> {
    public Account extractData(ResultSet rs) throws SQLException {
        //write result set to single domain object
        return account;
    }
}


                            Spring Framework - Data Access   Dmitry Noskov
Callback interfaces
   RowMapper
       each row to domain object
   RowCallbackHandler
       another output stream
   ResultSetExtructor
       multiple rows to domain object




                         Spring Framework - Data Access   Dmitry Noskov
Insert / Update / Delete

jdbcTemplate.update(
    "insert into accounts(account_id, account_owner) values(?, ?)",
    17, "Account Name");


jdbcTemplate.update(
    "update accounts set account_owner = ? where account_id = ?",
    "New Account Name", 18);


jdbcTemplate.update(
    "delete from accounts where account_id = ?", 19);




                           Spring Framework - Data Access   Dmitry Noskov
NamedParameterJdbcTemplate




        Spring Framework - Data Access   Dmitry Noskov
Creating the NamedJdbcTemplate

@Repository
public class AccountJdbcRepository implements AccountRepository {


    private NamedParameterJdbcTemplate namedJdbcTemplate;


    public AccountJdbcRepository(DataSource dataSource) {
        super();
        namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
    }
}




                             Spring Framework - Data Access   Dmitry Noskov
Naming parameters(1)

public Long getCountByName(String name) {
    Map<String, ?> params = Collections.singletonMap("name", name);
    String sql =
       "select count(*) from accounts where owner_name like :name";


    return namedJdbcTemplate.queryForLong(sql, params);
}




                           Spring Framework - Data Access   Dmitry Noskov
Naming parameters(2)
   map parameter source
    SqlParameterSource params = new MapSqlParameterSource("name","%ac%");
    namedJdbcTemplate.queryForInt(
        "select count(*) from accounts where owner_name like :name",
        params);

   bean parameter source
    Account acc = …;
    SqlParameterSource params = new BeanPropertySqlParameterSource(acc);


    namedJdbcTemplate.queryForInt(
      "select count(*) from m_accounts
       where account_name like :name and account_type = :type",
       params);



                            Spring Framework - Data Access   Dmitry Noskov
Batch operations




         Spring Framework - Data Access   Dmitry Noskov
Batch by jdbcTemplate
public void batchUpdate(final List<Account> accounts) {
    jdbcTemplate.batchUpdate(
      "update accounts set account_name = ?, account_type = ?
       where account_id = ?",
      new BatchPreparedStatementSetter() {
        public void setValues(PreparedStatement ps, int i) {
            ps.setString(1, accounts.get(i).getName());
            ps.setString(2, accounts.get(i).getType());
            ps.setLong(3, accounts.get(i).getId());
        }
        public int getBatchSize() {
            return accounts.size();
        }
      });
}

                             Spring Framework - Data Access   Dmitry Noskov
Batch by namedJdbcTemplate

public void batchUpdate2(final List<Account> accounts) {
    SqlParameterSource[] batch =
        SqlParameterSourceUtils.createBatch(accounts.toArray());


    namedJdbcTemplate.batchUpdate(
      "update m_accounts set account_name = :name, account_type = :type
       where account_id = :id",
      batch);
}




                           Spring Framework - Data Access   Dmitry Noskov
SimpleJdbcInsert

simpleJdbcInsert =
 new SimpleJdbcInsert(dataSource).withTableName("accounts");


Map<String, Object> params = new HashMap<String, Object>();
params.put("account_id", 12);
params.put("account_name", "name");
params.put("account_type", "type");


simpleJdbcInsert.execute(params);




                        Spring Framework - Data Access   Dmitry Noskov
Summary




          Spring Framework - Data Access   Dmitry Noskov
Spring Data Access
   promote layered architecture principles
   loose coupling between API and DAO layers
   supports top data access technologies
   flexible transaction management




                    Spring Framework - Data Access   Dmitry Noskov
Benefits of declarative transactions
   consistent model across different transaction APIs
     JTA
     JDBC

     JPA

     Hibernate

   supports for declarative transaction management
   simple API for programmatic transactions



                      Spring Framework - Data Access   Dmitry Noskov
Declarative transactions
   any environment
   any classes
   rollback rules
   customize transactional behavior

   not support transaction contexts across remote calls




                      Spring Framework - Data Access   Dmitry Noskov
Links
   Spring reference
       http://static.springsource.org/spring/docs/3.0.x/spring
        -framework-reference/html/spring-data-tier.html
   wiki: ACID
       http://en.wikipedia.org/wiki/ACID
   wiki: isolation
       http://en.wikipedia.org/wiki/Isolation_(database_systems)
   JTA
       http://en.wikipedia.org/wiki/Java_Transaction_API
                         Spring Framework - Data Access   Dmitry Noskov
Books




        Spring Framework - Data Access   Dmitry Noskov
Questions




            Spring Framework - Data Access   Dmitry Noskov
The end




             http://www.linkedin.com/in/noskovd

      http://www.slideshare.net/analizator/presentations

More Related Content

What's hot

I got 99 problems, but ReST ain't one
I got 99 problems, but ReST ain't oneI got 99 problems, but ReST ain't one
I got 99 problems, but ReST ain't oneAdrian Cole
 
The Beginner’s Guide To Spring Cloud
The Beginner’s Guide To Spring CloudThe Beginner’s Guide To Spring Cloud
The Beginner’s Guide To Spring CloudVMware Tanzu
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
React Context API
React Context APIReact Context API
React Context APINodeXperts
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Hitesh-Java
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureJosé Paumard
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6Rob Eisenberg
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 

What's hot (20)

I got 99 problems, but ReST ain't one
I got 99 problems, but ReST ain't oneI got 99 problems, but ReST ain't one
I got 99 problems, but ReST ain't one
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
The Beginner’s Guide To Spring Cloud
The Beginner’s Guide To Spring CloudThe Beginner’s Guide To Spring Cloud
The Beginner’s Guide To Spring Cloud
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
React Context API
React Context APIReact Context API
React Context API
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Express node js
Express node jsExpress node js
Express node js
 
Spring boot
Spring bootSpring boot
Spring boot
 
Apache Maven 3
Apache Maven 3Apache Maven 3
Apache Maven 3
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 

Viewers also liked

Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
Spring Framework - Web Flow
Spring Framework - Web FlowSpring Framework - Web Flow
Spring Framework - Web FlowDzmitry Naskou
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring SecurityDzmitry Naskou
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - ValidationDzmitry Naskou
 
Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression LanguageDzmitry Naskou
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesBrett Meyer
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewBrett Meyer
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Spring Boot Lightning Talk
Spring Boot Lightning TalkSpring Boot Lightning Talk
Spring Boot Lightning TalkRoger Diller
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction ManagementYe Win
 
Construção de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em JavaConstrução de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em JavaFernando Camargo
 
Banco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase LiteBanco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase LiteFernando Camargo
 
Boas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful APIBoas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful APIFernando Camargo
 
Effective Spring Transaction Management
Effective Spring Transaction ManagementEffective Spring Transaction Management
Effective Spring Transaction ManagementUMA MAHESWARI
 

Viewers also liked (20)

Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Spring Framework - Web Flow
Spring Framework - Web FlowSpring Framework - Web Flow
Spring Framework - Web Flow
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - Validation
 
Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression Language
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Spring Boot Lightning Talk
Spring Boot Lightning TalkSpring Boot Lightning Talk
Spring Boot Lightning Talk
 
Hibernate教程
Hibernate教程Hibernate教程
Hibernate教程
 
Transaction isolation levels
Transaction isolation levelsTransaction isolation levels
Transaction isolation levels
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction Management
 
Construção de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em JavaConstrução de Frameworks com Annotation e Reflection API em Java
Construção de Frameworks com Annotation e Reflection API em Java
 
Banco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase LiteBanco de dados no Android com Couchbase Lite
Banco de dados no Android com Couchbase Lite
 
Boas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful APIBoas práticas no desenvolvimento de uma RESTful API
Boas práticas no desenvolvimento de uma RESTful API
 
Effective Spring Transaction Management
Effective Spring Transaction ManagementEffective Spring Transaction Management
Effective Spring Transaction Management
 
Design de RESTful APIs
Design de RESTful APIsDesign de RESTful APIs
Design de RESTful APIs
 

Similar to Spring Framework - Data Access Overview

Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersoazabir
 
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File ServerUKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File ServerMarco Gralike
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5Smita B Kumar
 
Dropwizard Introduction
Dropwizard IntroductionDropwizard Introduction
Dropwizard IntroductionAnthony Chen
 
Construindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVC
Construindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVCConstruindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVC
Construindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVCEmmanuel Neri
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3IMC Institute
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2Haroon Idrees
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedIMC Institute
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRPeter Elst
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
Spring Cairngorm
Spring CairngormSpring Cairngorm
Spring Cairngormdevaraj ns
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.pptDrMeenakshiS
 
Creating Flexible Data Services For Enterprise Soa With Wso2 Data Services
Creating Flexible Data Services For Enterprise Soa With Wso2 Data ServicesCreating Flexible Data Services For Enterprise Soa With Wso2 Data Services
Creating Flexible Data Services For Enterprise Soa With Wso2 Data Servicessumedha.r
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 

Similar to Spring Framework - Data Access Overview (20)

Lecture17
Lecture17Lecture17
Lecture17
 
Unit 07: Design Patterns and Frameworks (3/3)
Unit 07: Design Patterns and Frameworks (3/3)Unit 07: Design Patterns and Frameworks (3/3)
Unit 07: Design Patterns and Frameworks (3/3)
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of users
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Jdbc
JdbcJdbc
Jdbc
 
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File ServerUKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
 
Dropwizard Introduction
Dropwizard IntroductionDropwizard Introduction
Dropwizard Introduction
 
Construindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVC
Construindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVCConstruindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVC
Construindo APIs de forma produtiva com Spring Boot, Spring Data e Spring MVC
 
Jdbc
JdbcJdbc
Jdbc
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet Advanced
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIR
 
JDBC
JDBCJDBC
JDBC
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Spring Cairngorm
Spring CairngormSpring Cairngorm
Spring Cairngorm
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Creating Flexible Data Services For Enterprise Soa With Wso2 Data Services
Creating Flexible Data Services For Enterprise Soa With Wso2 Data ServicesCreating Flexible Data Services For Enterprise Soa With Wso2 Data Services
Creating Flexible Data Services For Enterprise Soa With Wso2 Data Services
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 

Recently uploaded

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 

Recently uploaded (20)

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 

Spring Framework - Data Access Overview

  • 1. Spring Framework - Data Access SPRING FRAMEWORK 3.0 Dmitry Noskov Data Access
  • 2. Spring Data Access  DAO support  transaction management  JDBC  not included  ORM  marshalling XML Spring Framework - Data Access Dmitry Noskov
  • 3. DAO support jdbc namespace Spring data access exceptions Spring Framework - Data Access Dmitry Noskov
  • 4. JDBC namespace <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation=" http://www.springframework.org/schema/ beans http://www.springframework.org/schema/ beans/spring-beans-3.0.xsd http://www.springframework.org/schema/ jdbc http://www.springframework.org/schema/ jdbc/spring-jdbc-3.0.xsd"> </beans> Spring Framework - Data Access Dmitry Noskov
  • 5. Embedded database <jdbc:embedded-database id="dataSource" type="HSQL|H2|Derby"> <jdbc:script location="classpath:db-schema.sql"/> <jdbc:script location="classpath:test-data.sql"/> </jdbc:embedded-database> <bean class="org.exhanger.repository.jdbc.AccountJdbcRepository"> <property name="dataSource" ref="dataSource"/> </bean> Spring Framework - Data Access Dmitry Noskov
  • 6. Populate other DataSource <bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource"> <property name="URL" value="${jdbc.url}"/> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <jdbc:initialize-database data-source="dataSource" > <jdbc:script location="classpath:db-schema.sql"/> <jdbc:script location="classpath:test-data.sql"/> </jdbc:initialize-database> Spring Framework - Data Access Dmitry Noskov
  • 7. Problem of handling exceptions  exceptions  checked  unchecked  SQLException  technology-specific  depends on DBMS  couple the DAO and API Spring Framework - Data Access Dmitry Noskov
  • 8. Spring DataAccessException’s  unchecked  hide data access technology  JDBC  Hibernate  etc.  hide DBMS error codes Spring Framework - Data Access Dmitry Noskov
  • 9. DataAccessException hierarchy RuntimeException DataAccessException CleanupFailure DataIntegrity DataAccessException ViolationException OptimisticLocking DeadlockLoser FailureException DataAccessException DataAccessResource more… FailureException Spring Framework - Data Access Dmitry Noskov
  • 10. @Repository @Repository public class AccountJdbcRepository implements AccountRepository { @Autowired private DataSource dataSource; private JdbcTemplate jdbcTemplate; @Autowired public AccountJdbcRepository(DataSource dataSource) { super this.jdbcTemplate = new JdbcTemplate(dataSource); } } Spring Framework - Data Access Dmitry Noskov
  • 11. Transaction management Overview Transaction models Spring PlatformTransactionManager’s Spring Framework - Data Access Dmitry Noskov
  • 12. Unit of work public Long process(Account account, Order o) { String owner = o.getOwner(); String from = o.getFrom(); String to = o.getTo(); accountService.reduceBalance(account, to, o.getValue() * o.getRate()); accountService.increaseBalance(account, from, o.getValue()); accountService.reduceBalance(owner, from, o.getValue()); accountService.increaseBalance(owner, to, o.getValue() * o.getRate()); orderService.completeOrder(order.getId()); return auditService.createRecord(account, o); } Spring Framework - Data Access Dmitry Noskov
  • 13. ACID principles  atomicity  "all or nothing" rule for unit of work  consistency  only consistent data will be saved  isolation  isolating transactions for each other  durability  commited changes are permanent Spring Framework - Data Access Dmitry Noskov
  • 14. Transaction models  local  work across single transactional resource  resource-specific  easier to use  global  work across multiple transactional resources Spring Framework - Data Access Dmitry Noskov
  • 15. Local transactions  can be managed by DBMS, etc.  depends on connection Spring Framework - Data Access Dmitry Noskov
  • 16. Classic database transaction public class AccountJdbcRepository implements AccountRepository { private DataSource dataSource; public void modifyAccount(Account account) { String sql = "..."; Connection conn = null; try { conn = dataSource.getConnection(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement(sql); s.executeUpdate(); conn.commit(); } catch (SQLException e) { conn.rollback(); } } Spring Framework - Data Access Dmitry Noskov
  • 17. Problems with local transactions  connection management code is error-prone  transaction demarcation belongs at the service layer  multiple data access methods may be called within a transaction  connection must be managed at a higher level Spring Framework - Data Access Dmitry Noskov
  • 18. Spring transaction management  declarative  XML  annotations  programmatic Spring Framework - Data Access Dmitry Noskov
  • 19. Namespace <beans xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans/ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> </beans> Spring Framework - Data Access Dmitry Noskov
  • 20. Basic configuration <beans> <tx:annotation-driven transaction-manager="transactionManager" mode="proxy|aspectj" order="0" <!-- Ordered.LOWEST_PRECEDENCE --> proxy-target-class="false"/> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- <tx:jta-transaction-manager/> --> </beans> Spring Framework - Data Access Dmitry Noskov
  • 21. PlatformTransactionManager PlatformTransactionManager DataSourceTransactionManager JtaTransactionManager HibernateTransactionManager WebLogicJtaTransactionManager WebSphereUowTransactionManager Spring Framework - Data Access Dmitry Noskov
  • 22. @Transactional @Transactional public class AccountServiceImpl implements AccountService { @Transactional public Account getAccount(Long accountId) { return repository.getAccount(accountId); } @Transactional public Long createAccount(Account account) { return repository.createAccount(account); } } Spring Framework - Data Access Dmitry Noskov
  • 23. How it works Spring Framework - Data Access Dmitry Noskov
  • 24. Transactional attributes  propagation  isolation  rollback rules  read-only  timeout Spring Framework - Data Access Dmitry Noskov
  • 25. Transaction propagation(1)  REQUIRED  support a current transaction, create a new one if none exists @Transactional(propagation = Propagation.REQUIRED) public Long process(Account account, Order order){}  REQUIRED_NEW  create a new transaction, suspend the current if one exists @Transactional(propagation = Propagation.REQUIRED_NEW) public Long process(Account account, Order order){}  NESTED  single physical transaction with multiple savepoints Spring Framework - Data Access Dmitry Noskov
  • 26. REQUIRED Spring Framework - Data Access Dmitry Noskov
  • 27. REQUIRED_NEW Spring Framework - Data Access Dmitry Noskov
  • 28. Transaction propagation(2)  SUPPORTS  support a current transaction, or execute non-transactionally  MANDATORY  support a current transaction, throw an exception if none exists  NOT_SUPPORTED  execute non-transactionally, suspend the current transaction  NEVER  execute non-transactionally, throw an exception if a transaction exists Spring Framework - Data Access Dmitry Noskov
  • 29. Isolation levels  levels  READ_UNCOMMITED  READ_COMMITED  REPEATABLE_READ  SERIALIZABLE  DBMS  have differences in implementation  may not support something Spring Framework - Data Access Dmitry Noskov
  • 30. READ_UNCOMMITED  lowest isolation level  dirty reads are allowed  example @Transactional(isolation = Isolation.READ_UNCOMMITTED) public Order getOrder(Long orderId) { return repository.getOrder(orderId); } Spring Framework - Data Access Dmitry Noskov
  • 31. READ_COMMITED  default strategy for most DBMSs  only commited data can be accessed  example @Transactional(isolation = Isolation.READ_COMMITTED) public Order getOrder(Long orderId) { return repository.getOrder(orderId); } Spring Framework - Data Access Dmitry Noskov
  • 32. Highest isolation levels  REPEATABLE_READ  prevents non-repeatable reads  SERIALIZABLE  prevents phantom reads Spring Framework - Data Access Dmitry Noskov
  • 33. Rollback rules @Service public class AccountServiceImpl implements AccountService { @Transactional(rollbackFor = CheckedException.class) public Long createAccount(Account account) { return repository.createAccount(account); } @Transactional(noRollbackFor = SendNotificationException.class) public void modifyAccount(Account account) { repository.modifyAccount(account); } } Spring Framework - Data Access Dmitry Noskov
  • 34. Read-only transactions  optimize resource for read-only access  example @Transactional(readOnly = true) public Account getAccount(Long accountId) { return repository.getAccount(accountId); } Spring Framework - Data Access Dmitry Noskov
  • 35. Trsnsaction timeout  example @Transactional(timeout = 60) public List<Order> getActiveOrders(String from, String to) { } Spring Framework - Data Access Dmitry Noskov
  • 36. Multiple transaction managers <tx:annotation-driven/> <bean id="transactionManager1" class="..."> <qualifier value="txManager1"/> </bean> <bean id="transactionManager2" class="..."> <qualifier value="txManager2"/> </bean> @Transactional(value = "txManager1") public BigDecimal method1 (Order order) {} @Transactional(value = "txManager2") public Account merge(Account account) {} Spring Framework - Data Access Dmitry Noskov
  • 37. Custom shortcut annotations @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Transactional("txManager1") public @interface OrderTx {} @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Transactional("txManager2") public @interface AccountTx {} Using: @OrderTx public BigDecimal method1 (Order order) {} @AccountTx public Account merge(Account account) {} Spring Framework - Data Access Dmitry Noskov
  • 38. Programmatic transactions  TransactionTemplate  PlatformTransactionManager Spring Framework - Data Access Dmitry Noskov
  • 39. TransactionTemplate(1) public class AccountServiceImpl implements AccountService { private final TransactionTemplate template; private AccountServiceImpl(PlatformTransactionManager manager) { template = new TransactionTemplate(manager); } public Object method1(final Object obj) { return template.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus status) { return operation(obj); } }); } Spring Framework - Data Access Dmitry Noskov
  • 40. TransactionTemplate(2) public class AccountServiceImpl implements AccountService { private final TransactionTemplate template; private AccountServiceImpl(PlatformTransactionManager manager) { template = new TransactionTemplate(manager); } public void method2(final Object obj) { template.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus st){ operation(obj); } }); } Spring Framework - Data Access Dmitry Noskov
  • 41. TransactionTemplate(3) public class AccountServiceImpl implements AccountService { private final TransactionTemplate template; public void method3(final Object obj) { template.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus s){ try { operation(obj); } catch (RuntimeException e) { status.setRollbackOnly(); } } ); } Spring Framework - Data Access Dmitry Noskov
  • 42. PlatformTransactionManager public interface PlatformTransactionManager { /** Return a currently active transaction or create a new one, according to the specified propagation behavior. */ TransactionStatus getTransaction(TransactionDefinition definition); /** Commit the given transaction, with regard to its status. If the transaction has been marked rollback-only programmatically, perform a rollback. */ void commit(TransactionStatus status); /** Perform a rollback of the given transaction. */ void rollback(TransactionStatus status); } Spring Framework - Data Access Dmitry Noskov
  • 43. XML-based <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="*" propagation="REQUIRED" isolation="READ_COMMITTED" rollback-for="java.lang.Throwable" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="txOperation" expression="execution(* org.training.api..*ServiceImpl.*(..))"/> <aop:advisor pointcut-ref="txOperation" advice-ref="txAdvice" order="" /> </aop:config> Spring Framework - Data Access Dmitry Noskov
  • 44. Spring JDBC Spring Framework - Data Access Dmitry Noskov
  • 45. Strong JDBC public List<Account> getAccountsByType(Long type) { List<Account> accounts = new ArrayList<Account>(); Connection connection = null; String sql = "select account_id, account_owner from account"; try { connection = dataSource.getConnection(); PreparedStatement ps = connection.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()) { accounts.add(new Account(rs.getLong(1), rs.getString(2))); } } catch (SQLException e) {/*handle exception*/} finally { try { connection.close();} catch (SQLException e) {/*handle*/} } return accounts; } Spring Framework - Data Access Dmitry Noskov
  • 46. Target code public List<Account> getAccountsByType(Long type) { List<Account> accounts = new ArrayList<Account>(); Connection connection = null; String sql = "select account_id, account_owner from account"; try { connection = dataSource.getConnection(); PreparedStatement ps = connection.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()) { accounts.add(new Account(rs.getLong(1), rs.getString(2))); } } catch (SQLException e) {/*handle exception*/} finally { try { connection.close();} catch (SQLException e) {/*handle*/} } return accounts; } Spring Framework - Data Access Dmitry Noskov
  • 47. Who does what Action Spring You Define connection parameters X Connection management X SQL X Statement management X ResultSet management X Row Data Retrieval X Exception handling X Handle transactions X Spring Framework - Data Access Dmitry Noskov
  • 48. Spring JDBC abstractions JdbcTemplate NamedParameterJdbcTemplate SimpleJdbcTemplate SimpleJdbcInsert and SimpleJdbcCall Spring Framework - Data Access Dmitry Noskov
  • 49. JdbcTemplate Spring Framework - Data Access Dmitry Noskov
  • 50. Creating the JdbcTemplate @Repository public class AccountJdbcRepository implements AccountRepository { private JdbcTemplate jdbcTemplate; public AccountJdbcRepository(DataSource dataSource) { super(); jdbcTemplate = new JdbcTemplate(dataSource); } } Spring Framework - Data Access Dmitry Noskov
  • 51. Simple types int intCount = jdbcTemplate.queryForInt("select count(*) from accounts"); int longCount = jdbcTemplate.queryForLong ( "select count(*) from accounts where account_owner like ?", "name"); String name = jdbcTemplate.queryForObject( "select account_owner from accounts where account_id = ?", new Object[]{10}, String.class); Spring Framework - Data Access Dmitry Noskov
  • 52. Generic maps public Map<String, Object> getAccount(Long accountId) { String sql = "select * from accounts where account_id = ?"; return jdbcTemplate.queryForMap(sql, accountId); } public List<Map<String, Object>> getAccounts() { return jdbcTemplate.queryForList("select * from accounts"); } Spring Framework - Data Access Dmitry Noskov
  • 53. Domain object(1) Account account = jdbcTemplate.queryForObject( "select account_id, account_owner from accounts where account_id = ?", new Object[]{11}, new RowMapper<Account>(){ public Account mapRow(ResultSet rs, int rowNum){ Account account = new Account(); account.setId(rs.getLong("account_id")); account.setOwner (rs.getString("account_owner")); return account; } }); Spring Framework - Data Access Dmitry Noskov
  • 54. Domain object(2) List<Account> accounts = jdbcTemplate.query( "select account_id, account_name from m_accounts where account_id = ?", new Object[]{11}, new RowMapper<Account>(){ public Account mapRow(ResultSet rs, int rowNum) { Account account = new Account(); account.setId(rs.getLong("account_id")); account.setName(rs.getString("account_name")); return account; } }); Spring Framework - Data Access Dmitry Noskov
  • 55. Callback handler public void writeAccountsToFile(File f) { jdbcTemplate.query("select * from account", new FileWriter(f)); } public class FileWriter implements RowCallbackHandler { public FileWriter(File file) { super(); } public void processRow(ResultSet rs) throws SQLException { //write result set to file } } Spring Framework - Data Access Dmitry Noskov
  • 56. ResultSet extractor public Account getAccount(long accountId) { String sql = "select * from accounts where account_id = ?"; return jdbcTemplate.query(sql, new Object[]{accountId}, new Extractor()); } public class Extractor implements ResultSetExtractor<Account> { public Account extractData(ResultSet rs) throws SQLException { //write result set to single domain object return account; } } Spring Framework - Data Access Dmitry Noskov
  • 57. Callback interfaces  RowMapper  each row to domain object  RowCallbackHandler  another output stream  ResultSetExtructor  multiple rows to domain object Spring Framework - Data Access Dmitry Noskov
  • 58. Insert / Update / Delete jdbcTemplate.update( "insert into accounts(account_id, account_owner) values(?, ?)", 17, "Account Name"); jdbcTemplate.update( "update accounts set account_owner = ? where account_id = ?", "New Account Name", 18); jdbcTemplate.update( "delete from accounts where account_id = ?", 19); Spring Framework - Data Access Dmitry Noskov
  • 59. NamedParameterJdbcTemplate Spring Framework - Data Access Dmitry Noskov
  • 60. Creating the NamedJdbcTemplate @Repository public class AccountJdbcRepository implements AccountRepository { private NamedParameterJdbcTemplate namedJdbcTemplate; public AccountJdbcRepository(DataSource dataSource) { super(); namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); } } Spring Framework - Data Access Dmitry Noskov
  • 61. Naming parameters(1) public Long getCountByName(String name) { Map<String, ?> params = Collections.singletonMap("name", name); String sql = "select count(*) from accounts where owner_name like :name"; return namedJdbcTemplate.queryForLong(sql, params); } Spring Framework - Data Access Dmitry Noskov
  • 62. Naming parameters(2)  map parameter source SqlParameterSource params = new MapSqlParameterSource("name","%ac%"); namedJdbcTemplate.queryForInt( "select count(*) from accounts where owner_name like :name", params);  bean parameter source Account acc = …; SqlParameterSource params = new BeanPropertySqlParameterSource(acc); namedJdbcTemplate.queryForInt( "select count(*) from m_accounts where account_name like :name and account_type = :type", params); Spring Framework - Data Access Dmitry Noskov
  • 63. Batch operations Spring Framework - Data Access Dmitry Noskov
  • 64. Batch by jdbcTemplate public void batchUpdate(final List<Account> accounts) { jdbcTemplate.batchUpdate( "update accounts set account_name = ?, account_type = ? where account_id = ?", new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int i) { ps.setString(1, accounts.get(i).getName()); ps.setString(2, accounts.get(i).getType()); ps.setLong(3, accounts.get(i).getId()); } public int getBatchSize() { return accounts.size(); } }); } Spring Framework - Data Access Dmitry Noskov
  • 65. Batch by namedJdbcTemplate public void batchUpdate2(final List<Account> accounts) { SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(accounts.toArray()); namedJdbcTemplate.batchUpdate( "update m_accounts set account_name = :name, account_type = :type where account_id = :id", batch); } Spring Framework - Data Access Dmitry Noskov
  • 66. SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("accounts"); Map<String, Object> params = new HashMap<String, Object>(); params.put("account_id", 12); params.put("account_name", "name"); params.put("account_type", "type"); simpleJdbcInsert.execute(params); Spring Framework - Data Access Dmitry Noskov
  • 67. Summary Spring Framework - Data Access Dmitry Noskov
  • 68. Spring Data Access  promote layered architecture principles  loose coupling between API and DAO layers  supports top data access technologies  flexible transaction management Spring Framework - Data Access Dmitry Noskov
  • 69. Benefits of declarative transactions  consistent model across different transaction APIs  JTA  JDBC  JPA  Hibernate  supports for declarative transaction management  simple API for programmatic transactions Spring Framework - Data Access Dmitry Noskov
  • 70. Declarative transactions  any environment  any classes  rollback rules  customize transactional behavior  not support transaction contexts across remote calls Spring Framework - Data Access Dmitry Noskov
  • 71. Links  Spring reference  http://static.springsource.org/spring/docs/3.0.x/spring -framework-reference/html/spring-data-tier.html  wiki: ACID  http://en.wikipedia.org/wiki/ACID  wiki: isolation  http://en.wikipedia.org/wiki/Isolation_(database_systems)  JTA  http://en.wikipedia.org/wiki/Java_Transaction_API Spring Framework - Data Access Dmitry Noskov
  • 72. Books Spring Framework - Data Access Dmitry Noskov
  • 73. Questions Spring Framework - Data Access Dmitry Noskov
  • 74. The end http://www.linkedin.com/in/noskovd http://www.slideshare.net/analizator/presentations