quinta-feira, 22 de agosto de 2013

Spring with Data Base

From the book:
    Spring in Action 3rd Edition.
    Link to it-ebooks to Download


- Spring with Data Base
    Spring suports: JDBC, Hibernate, JPA(Java Persistence API), etc
    Objetivo do Spring e usar o conceito de interface do OO.  This is done in the Spring's data access
    Different from JDBC, Spring provides several data access exceptions rather than SQLException.
        The main exception DataAccessException is checked exception.
    Templating data access
        Two parts
            fixed(templates)
                Controls transaction, manages resouces, handle exceptions
            variable(callbacks)              
                create statements, bind parameters, marshals result sets
            Steps
                1- Prepare resources
                2 - Start Transaction        3 - Excecute in tarnsaction
                                            4 - Return data
                5 - Commit/Rollback transaction
                6 - Closes resources and handle erros
        Several different kinds of templates? JDBCTempale, HibernateTemplate, JpaTemplate, etc
    Configuring a data source
        Main options for configuring data source beans
        - JDBC Driver
            Two data source classes to choose?
                - DriverManagerDataSource: Returns a niew connection every time that a connection is requested.  No pool
                - SingleConnectionDataSource: Return the same connection every time a connection is requested.
                <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                    <propertyname="driverClassName"
                    value="org.hsqldb.jdbcDriver"/>
                    <propertyname="url"
                    value="jdbc:hsqldb:hsql://localhost/spitter/spitter"/>
                    <propertyname="username"value="sa"/>
                    <propertyname="password"value=""/>
                </bean>      
                - Good for small applications or development.
        - look up by JNDI
            Usually in a Java EE application server/container.
            Configuration can be managed completely external
            <jee:jndi-lookupid="dataSource"
                jndi-name="/jdbc/SpitterDS"
            resource-ref="true"/>              
        - pool connections
            Uses Jakarta Commons Database connection Pooling(DBCP)
            Includes several data sources that provide pooling. Most used = BasicDataSource(similar to DriverManagerDataSource)
            <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
                <propertyname="driverClassName"value="org.hsqldb.jdbcDriver"/>
                <propertyname="url" value="jdbc:hsqldb:hsql://localhost/spitter/spitter"/>
                <propertyname="username"value="sa"/>
                <propertyname="password"value=""/>
                <propertyname="initialSize"value="5"/>
                <propertyname="maxActive"value="10"/>
            </bean>              
       
    Using JDBC with Spring
        - Dont require mastering another framework's query language
        - It's built on top of SQL
        - Take advantage of database's proprietary features
        - Lets you work with data as a lower level than any framework
            private static final String SQL_INSERT_SPITTER= "insert into spitter(username,password,fullname)values(?,?,?)";
            private DataSourcedataSource;
                public voidaddSpitter(Spitterspitter){
                    Connectionconn=null;
                    PreparedStatementstmt=null;          
                    try {
                        conn =dataSource.getConnection();
                        stmt =conn.prepareStatement(SQL_INSERT_SPITTER);
                        stmt.setString(1,spitter.getUsername());
                        stmt.setString(2,spitter.getPassword());
                        stmt.setString(3,spitter.getFullName());
                        stmt.execute();
                    }.... finally, SQLException....
                }
        JDBC Templates (Three templates classes)
            - JdbcTemplate: Most basic of Spring's JDBC templates.
                Provide simple access to a database through JDBC and simple indexed-parameter queries
            - NamedParameterJdbcTemplate:
                Enables you to perform queries where values are bound to named parameters in SQL, rather than indexed parameters
            - SimpleJdbcTemplate: (Most important)
                Take advantage of Java 5 with autoboxing, generics and variable parameter lists
                <bean id="jdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
                    <constructor-argref="dataSource"/>
                </bean>
                ....
                public classJdbcSpitterDAO implements SpitterDAO{
                    ...
                    privateSimpleJdbcTemplatejdbcTemplate;
                    public voidsetJdbcTemplate(SimpleJdbcTemplatejdbcTemplate){
                        this.jdbcTemplate=jdbcTemplate;
                    }
                    public voidaddSpitter(Spitterspitter){
                        jdbcTemplate.update(SQL_INSERT_SPITTER,
                            spitter.getUsername(),
                            spitter.getPassword(),
                            spitter.getFullName(),
                            spitter.getEmail(),
                            spitter.isUpdateByEmail());
                            spitter.setId(queryForIdentity());
                    }
                   
                    public SpittergetSpitterById(longid){
                        return jdbcTemplate.queryForObject(
                        SQL_SELECT_SPITTER_BY_ID,
                        new ParameterizedRowMapper<Spitter>(){
                            public Spitter mapRow(ResultSet rs,int rowNum) <- para cada linha cria um Spitter dentro do resultSet
                                throws SQLException{
                                    Spitter spitter=newSpitter();
                                    spitter.setId(rs.getLong(1));
                                    spitter.setUsername(rs.getString(2));
                                    spitter.setPassword(rs.getString(3));
                                    spitter.setFullName(rs.getString(4));
                                    return spitter;
                                }
                            },
                            id
                        );
                    }
                }
                - How to access the template via DAO
                <bean id="spitterDao" class="com.habuma.spitter.persistence.SimpleJdbcTemplateSpitterDao">
                    <propertyname="jdbcTemplate"ref="jdbcTemplate"/>
                </bean>
            - DAO Support Classes for JDBC
                - public class JdbcSpitterDao extends SimpleJdbcDaoSupport implements SpitterDao {
                    public void addSpitter(Spitter spitter){
                        getSimpleJdbcTemplate().update(SQL_INSERT_SPITTER,
                            spitter.getUsername(),
                            spitter.getPassword(),
                            spitter.getFullName(),
                            spitter.getEmail(),
                            spitter.isUpdateByEmail());
                        spitter.setId(queryForIdentity());
                    }
                 }
                 <bean id="spitterDao" class="com.habuma.spitter.persistence.JdbcSpitterDao">
                    <property name="jdbcTemplate" ref="jdbcTemplate"/>
                </bean>
    Hibernate with Spring
        Services
            - Integrated support for Spring declarative transactions
            - Transparent exception handling
            - Thread-safe, lightweight template classes
            - DAO support classes
            - Resource management
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="mappingResources">
                <list>
                    <value>Spitter.hbm.xml</value>  <<----  Indicates where find the database
                </list>
            </property>
            <property name="hibernateProperties">
                <props>
                <prop key="dialect">org.hibernate.dialect.HSQLDialect</prop>
                </props>
            </property>
        </bean>
         To use annotation-oriented persistence use AnnotationSessionFactoryBean instead of LocalSessionFactoryBean:
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
            <propertyname="dataSource"ref="dataSource"/>
            <property name="packagesToScan" value="com.habuma.spitter.domain"/>  <<<----  Scan the domain classes that are annotated for persistence with Hibernate
            OR
            <propertyname="packagesToScan">
                <list>
                    <value>com.habuma.spitter.domain</value>
                </list>
            </property>
            <property name="hibernateProperties">
                <props>
                    <propkey="dialect">org.hibernate.dialect.HSQLDialect</prop>
                </props>
            </property>
        </bean>
       
         packagesToScan
            Scan the domain classes that are annotated for persistence with Hibernate.
            Annotations can be     @Entity or @MappedSuperClass.
           
        Spring-Free Hibernate
            Ex:
                @Repository
                public class HibernateSpitterDao implements SpitterDao{
                    privateSessionFactorysessionFactory;
                    @Autowired  <<---  Pegaria a session já criada automaticamente.
                    public HibernateSpitterDao(SessionFactory sessionFactory){    this.sessionFactory=sessionFactory;    } <--- Constructor
                   
                    private Session currentSession(){    return sessionFactory.getCurrentSession(); } Retrieve the Current Session
                    public void addSpitter(Spitterspitter){    currentSession().save(spitter);    }
                    public Spitter getSpitterById(longid){ return(Spitter)currentSession().get(Spitter.class,id); }
                    public void saveSpitter(Spitterspitter){    currentSession().update(spitter);    }
                    ...
                }
            With <context:component-scan>, it is not necessary to explicit a DAO class in xml config.  You can just use @Repository
                    <context:component-scan base-package="com.habuma.spitter.persistence"/>
        JPA (Java Persistence API)
            - Two kind of persistence managers (both implements EntityManager)
                - Application-managed: Entity managers are created when a application directly request one from the factory.  Application is responsible
                    for opening and closing entity managers and the transaction.  Most apropriate for use in standalone applications that dont run in a J2EE container.
                - Container-managed: Entity managers are created and managed by the J2EE container.  App doesnt interact with the factory.  
                    Entity managers are obtained from JNDI.
            - Configure Application-managed JPA (persistence.xml)
            <persistencexmlns="http://java.sun.com/xml/ns/persistence"    version="1.0">
                <persistence-unit name="spitterPU">      <<<<--------------------------- unit name
                    <class>com.habuma.spitter.domain.Spitter</class>
                    <class>com.habuma.spitter.domain.Spittle</class>
                    <properties>
                        <property name="toplink.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
                        <property name="toplink.jdbc.url"value="jdbc:hsqldb:hsql://localhost/spitter/spitter"/>
                        <property name="toplink.jdbc.user"value="sa" />
                        <property name="toplink.jdbc.password"value="" />
                    </properties>
                </persistence-unit>
            </persistence>
            <bean id="emf" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
                <property name="persistenceUnitName"value="spitterPU"/>  <<<<--------------------------- unit name
            </bean>

Nenhum comentário:

Postar um comentário