Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Spring Capitulo 04

5,816 views

Published on

  • Hi there! Get Your Professional Job-Winning Resume Here - Check our website! http://bit.ly/resumpro
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Spring Capitulo 04

  1. 3. <ul><li>Conhecer a árvore hierárquica de Exceptions do Spring </li></ul><ul><li>Saber criar um DataSource </li></ul><ul><li>Conhecer as principais funcionalidades do JdbcTemplate </li></ul><ul><li>Saber utilizar o SessionFactoryBean </li></ul><ul><li>Conhecer as principais funcionalidades do HibernateTemplate </li></ul>
  2. 4. <ul><li>Saber utilizar transações declarativas </li></ul>
  3. 5. <ul><ul><li>Exceptions do Spring </li></ul></ul><ul><ul><li>Unchecked </li></ul></ul><ul><ul><li>Tradução de SQLException para uma mais específica. </li></ul></ul><ul><ul><li>JDO, JPA, Hibernate e JDBC estão na mesma árvore de exeptions </li></ul></ul><ul><ul><li>Facilidade para trocar o mecanismo de persistência </li></ul></ul><ul><ul><li>*DaoSupport </li></ul></ul>
  4. 6. <ul><li>JdbcDaoSupport : Super classe para acesso via JDBC, necessita um DataSource, prove um instância de JDBCTemplate. </li></ul><ul><li>HibernateDaoSupport: Super classe de acesso via Hibernate, necessita uma SessionFactory, prove uma instância de HibernateTemplate. </li></ul><ul><li>JdoDaoSupport: Super classe de acesso via JDO, necessita uma PersistenceManagerFactory, prove uma instância de JdoTemplate. </li></ul><ul><li>JpaDaoSupport : Super classe de acesso via JDO, necessita uma EntityManagerFactory, prove uma instância de JpaTemplate. </li></ul>
  5. 8. <ul><ul><li>Parte da Especificação Jdbc </li></ul></ul><ul><ul><li>Permite “esconder” problemas de: </li></ul></ul><ul><ul><ul><li>Gerenciamento transacional </li></ul></ul></ul><ul><ul><ul><li>Pools de conexões </li></ul></ul></ul><ul><ul><ul><li>Pode se usar uma fonte JNDI </li></ul></ul></ul><ul><ul><ul><li>DriverManagerDataSource: </li></ul></ul></ul><ul><ul><ul><ul><li>Simples </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Genérica </li></ul></ul></ul></ul><ul><ul><ul><ul><li>Não tem pool </li></ul></ul></ul></ul>
  6. 9. <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> < beans xmlns = &quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi = &quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation = &quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot; > < bean id = &quot;dataSource” class = &quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot; lazy-init = &quot;false&quot; > < property name = &quot;driverClassName&quot; value = &quot;org.hsqldb.jdbcDriver&quot; /> < property name = &quot;url&quot; value = &quot;jdbc:hsqldb:hsql://C:/db&quot; /> < property name = &quot;username&quot; value = &quot;sa&quot; /> < property name = &quot;password&quot; value = &quot;&quot; /> </ bean > </ beans >
  7. 10. <ul><ul><li>Template Jdbc </li></ul></ul><ul><ul><li>Métodos utilitários </li></ul></ul><ul><ul><li>Orientado a DataSource </li></ul></ul><ul><ul><li>Tem suporte ao certo nível de “orm” </li></ul></ul><ul><ul><li>Query com retornos refinados </li></ul></ul><ul><ul><li>Callbacks </li></ul></ul>
  8. 11. <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> < beans xmlns = &quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi = &quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation = &quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot; > < bean id = &quot;dataSource&quot; class = &quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot; lazy-init = &quot;false&quot; > < property name = &quot;driverClassName&quot; value = &quot;org.hsqldb.jdbcDriver&quot; /> < property name = &quot;url” value = &quot;jdbc:hsqldb:file:///C:argetpringb&quot; /> < property name = &quot;username&quot; value = &quot;sa&quot; /> < property name = &quot;password“ value = &quot;&quot; /> </ bean > < bean id = &quot;jdbcTemplate&quot; class = &quot;org.springframework.jdbc.core.JdbcTemplate&quot; lazy-init = &quot;false&quot; > < property name = &quot;dataSource&quot; ref = &quot;dataSource&quot; /> < property name = &quot;lazyInit&quot; value = &quot;false&quot; /> </ bean > </ beans >
  9. 12. <ul><ul><li>Execute (String sql) </li></ul></ul><ul><ul><li>Update (String sql,Object[] args) </li></ul></ul><ul><ul><li>queryForObject (String sql,Class requiredType) </li></ul></ul><ul><ul><li>queryForObject (String sql,RowMapper rowMapper) </li></ul></ul><ul><ul><li>queryForInt (String sql) </li></ul></ul><ul><ul><li>queryForList (String sql) </li></ul></ul>
  10. 13. <ul><ul><li>Bean para gerenciar SessionFactory do Hibernate </li></ul></ul><ul><ul><li>LocalSessionFactoryBean </li></ul></ul><ul><ul><ul><li>DataSource </li></ul></ul></ul><ul><ul><ul><li>Hibernate mappings (via Spring) </li></ul></ul></ul><ul><ul><ul><li>Muito utilizado em aplicações JEE </li></ul></ul></ul>
  11. 14. <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> < beans xmlns = &quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi = &quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation = &quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot; > < bean id = &quot;dataSource&quot; class = &quot;org.springframework.jdbc.datasource.DriverManagerDataSource” lazy-init = &quot;false&quot; > < property name = &quot;driverClassName&quot; value = &quot;org.hsqldb.jdbcDriver&quot; /> < property name = &quot;url&quot; value = &quot;jdbc:hsqldb:file:///C:argetpringb&quot; /> < property name = &quot;username&quot; value = &quot;sa&quot; /> < property name = &quot;password&quot; value = &quot;&quot; /> </ bean > < bean id = &quot;sessionFactory&quot; class = &quot;org.springframework.orm.hibernate3.LocalSessionFactoryBean&quot; lazy-init = &quot;false&quot; > < property name = &quot;dataSource&quot; ref = &quot;dataSource&quot; /> < property name = &quot;mappingResources&quot; > < list > < value > com/targettrust/spring/hibernate/Pessoa.hbm.xml </ value > </ list > </ property > < property name = &quot;hibernateProperties&quot; > < props > < prop key = &quot;hibernate.dialect&quot; > org.hibernate.dialect.PointbaseDialect </ prop > < prop key = &quot;hibernate.hbm2ddl.auto&quot; > create </ prop > </ props > </ property > </ bean > </ beans >
  12. 15. <ul><ul><li>Dependências (jars): </li></ul></ul><ul><ul><ul><li>Hibernate3.jar </li></ul></ul></ul><ul><ul><ul><li>jta.jar </li></ul></ul></ul><ul><ul><ul><li>dom4j-1.6.1.jar </li></ul></ul></ul><ul><ul><ul><li>commons-logging.jar </li></ul></ul></ul><ul><ul><ul><li>commons-collections.jar </li></ul></ul></ul><ul><ul><ul><li>antlr-2.7.6.jar </li></ul></ul></ul><ul><ul><ul><li>mais Driver jdbc do Banco </li></ul></ul></ul>
  13. 16. <ul><ul><li>Template para o Hibernate </li></ul></ul><ul><ul><li>Necessita uma SessionFactory </li></ul></ul><ul><ul><li>Abre e Fecha SS </li></ul></ul><ul><ul><li>Participa de transações </li></ul></ul><ul><ul><li>Algums métodos: </li></ul></ul><ul><ul><ul><li>Find (String hql) </li></ul></ul></ul><ul><ul><ul><li>findByCriteria (DetachedCriteria d) </li></ul></ul></ul><ul><ul><ul><li>Delete (String hql) </li></ul></ul></ul><ul><ul><ul><li>saveOrUpdate </li></ul></ul></ul><ul><ul><ul><li>get </li></ul></ul></ul>
  14. 17. <ul><ul><li>Callbacks para acessar a SessionFactory do Hibernate, porém com as facilidades de: </li></ul></ul><ul><ul><ul><li>Abrir SS </li></ul></ul></ul><ul><ul><ul><li>Fechar SS </li></ul></ul></ul><ul><ul><ul><li>HibernateCallBack: execute </li></ul></ul></ul>
  15. 18. package com.targettrust.spring.hibernate; public class Pessoa { private Long id ; private String nome ; private String email ; // Getters e Setters } <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> <! DOCTYPE hibernate-mapping PUBLIC &quot;-//Hibernate/Hibernate Mapping DTD//EN&quot; &quot;http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd&quot; > < hibernate-mapping > < class name = &quot;com.targettrust.spring.hibernate.Pessoa&quot; table = &quot;pessoa&quot; > < id name = &quot;id&quot; column = &quot;id&quot; type = &quot;java.lang.Long&quot; unsaved-value = &quot;0&quot; > < generator class = &quot;increment&quot; /> </ id > < property name = &quot;nome&quot; column = &quot;nome&quot; type = &quot;java.lang.String&quot; /> < property name = &quot;email&quot; column = &quot;email&quot; type = &quot;java.lang.String&quot; /> </ class > </ hibernate-mapping >
  16. 19. <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> < beans xmlns = &quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi = &quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation = &quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot; > < bean id = &quot;dataSource” lazy-init = &quot;false” class = &quot;org.springframework.jdbc.datasource.DriverManagerDataSource“ > < property name = &quot;driverClassName&quot; value = &quot;org.hsqldb.jdbcDriver&quot; /> < property name = &quot;url&quot; value = &quot;jdbc:hsqldb:file:///C:argetpringb&quot; /> < property name = &quot;username&quot; value = &quot;sa&quot; /> < property name = &quot;password&quot; value = &quot;&quot; /> </ bean > < bean id = &quot;sessionFactory“ lazy-init = &quot;false&quot; class = &quot;org.springframework.orm.hibernate3.LocalSessionFactoryBean“ > < property name = &quot;dataSource&quot; ref = &quot;dataSource&quot; /> < property name = &quot;mappingResources&quot; > < list >< value > com/targettrust/spring/hibernate/Pessoa.hbm.xml </ value ></ list > </ property > < property name = &quot;hibernateProperties&quot; > < props > < prop key = &quot;hibernate.dialect&quot; > org.hibernate.dialect.PointbaseDialect </ prop > </ props > </ property > </ bean > < bean id = &quot;hibernateTemplate“ lazy-init = &quot;false” class = &quot;org.springframework.orm.hibernate3.HibernateTemplate“ > < property name = &quot;sessionFactory&quot; ref = &quot;sessionFactory&quot; /> </ bean > </ beans >
  17. 20. <ul><ul><li>Recurso disponivel apenas em containers JEE </li></ul></ul><ul><ul><li>Gerenciamento transacional declarativo para Jdbc( EJB não tem !!! ) </li></ul></ul><ul><ul><li>TransactionManager: HibernateTransacrtionManager </li></ul></ul><ul><ul><li>Interceptor AOP Proxy </li></ul></ul><ul><ul><li>Transação: Session Factory ThreadLocal(HibernateTransactionManager), mudar para JPA(transação Distribuída) sem mexer no código. </li></ul></ul>
  18. 21. <ul><ul><li>Abstração de Commit/Rollback </li></ul></ul><ul><ul><li>AutomaticosCommit/Rollback baseado em exceptions: </li></ul></ul><ul><ul><ul><li>Se nenhuma exception unchecked é levantada: commit </li></ul></ul></ul><ul><ul><ul><li>Se alguma exception unchecked é levantada por quem tem o proxy de transação: rollback </li></ul></ul></ul>
  19. 22. <ul><ul><li>Compatibilidade com modelo antigo Spring 1.x.x: TransactionProxyFactoryBean </li></ul></ul><ul><ul><li>HibernateTransactionManager: </li></ul></ul><ul><ul><ul><li>Expõe por DataSource </li></ul></ul></ul><ul><ul><ul><li>Mesma transação Entre: </li></ul></ul></ul><ul><ul><ul><ul><li>JDBC e Hibernate </li></ul></ul></ul></ul><ul><ul><ul><ul><li>De forma declarativa </li></ul></ul></ul></ul>
  20. 23. <ul><ul><li>Passos para criação: </li></ul></ul><ul><ul><ul><li>DataSource </li></ul></ul></ul><ul><ul><ul><li>SessionFactoryBean </li></ul></ul></ul><ul><ul><ul><li>HibernateTransactionManager </li></ul></ul></ul><ul><ul><ul><li>AOP Config </li></ul></ul></ul><ul><ul><ul><li>TxAdvice </li></ul></ul></ul>
  21. 24. <!-- Defini ç ão do Dataource para acesso ao banco HSQLDB --> < bean id = &quot;dataSource&quot; class = &quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot; lazy-init = &quot;false&quot; > < property name = &quot;driverClassName&quot; value = &quot;org.hsqldb.jdbcDriver&quot; /> < property name = &quot;url&quot; value = &quot;jdbc:hsqldb:file:///C:argetpringb&quot; /> <property name = &quot;username&quot; value = &quot;sa&quot; /> < property name = &quot;password&quot; value = &quot;&quot; /> </ bean >
  22. 25. <!-- Defini ç ão da SessionFactory do Hibernate --> < bean id = &quot;sessionFactory&quot; class = &quot;org.springframework.orm.hibernate3.LocalSessionFactoryBean&quot; lazy-init = &quot;false&quot; > < property name = &quot;dataSource&quot; ref = &quot;dataSource&quot; /> < property name = &quot;mappingResources&quot; > < list > < value > com/targettrust/spring/transaction/Produto.hbm.xml </ value > </ list > </ property > < property name = &quot;hibernateProperties&quot; > < props > < prop key = &quot;hibernate.dialect&quot; > org.hibernate.dialect.HSQLDialect </ prop > </ props > </ property ></ bean >
  23. 26. <!-- Defini ç ão do TransactionManager, nesse caso o escolhido para a tarefa de gerencia as transa ç ões foi o org.springframework.orm.hibernate3.HibernateTransactionManager que gerencia transa ç ões entre Hibernate e JDBC pelo DataSource --> < bean id = &quot;txManager&quot; class = &quot;org.springframework.orm.hibernate3.HibernateTransactionManager&quot; > < property name = &quot;sessionFactory&quot; ref = &quot;sessionFactory&quot; /> </ bean >
  24. 27. define os pontos do sistema que seram interceptados, nesse caso é a execu ç ão de qaulquer metodos do ProdutoService. Depois ele vincula essas classes interceptadas com um advice o txAdvice; --> < aop:config > < aop:pointcut id = &quot;produtoServiceMetodos&quot; expression = &quot;execution(* com.targettrust.spring.transaction.ProdutoService.*(..))&quot; /> < aop:advisor advice-ref = &quot;txAdvice&quot; pointcut-ref = &quot;produtoServiceMetodos&quot; /> </ aop:config >
  25. 28. <!-- Defini ç ão do Advide AOP que casa o gerente de transa ç ões com os metodos Esse beans informa que metodos e como esses metodos devem ser tratados pela transa ç ão --> < tx:advice id = &quot;txAdvice&quot; transaction-manager = &quot;txManager&quot; > < tx:attributes > < tx:method name = &quot;salvar*&quot; propagation = &quot;REQUIRED&quot; /> < tx:method name = &quot;findAll&quot; propagation = &quot;REQUIRED&quot; read-only = &quot;true&quot; /> </ tx:attributes ></ tx:advice >
  26. 29. <ul><li>Crei um Data Source para o banco de dados HSQLDB </li></ul><ul><li>Defina um Bean JDBCTemplate </li></ul><ul><li>Utilize o método queryForObject e liste todos os produtos </li></ul><ul><li>Faça um DAO que grave produtos utilizando transações declarativas e caso o produto a ser gravado tenha valor <= 0 levante uma exception para invalidar a operação após o save. </li></ul>

×