Spring Study[10]

the service objects are accessing the DAOs through interfaces.This has a couple of advantages. First, it makes your service objects easily testable since they are not coupled to a specific data access implementation.In addition, the data access tier is accessed in a persistence technology-agnostic manner.

Spring’s DAO frameworks do not throw technology-specific exceptions, such as SQLException or HibernateException. Instead, all exceptions thrown are subclasses of the technology-agnostic org.springframework.dao.DataAccessException.
DataAccessException is a RuntimeException, so it is an unchecked exception.

Working with DataSources:
In Spring’s DAO frameworks, Connection objects are obtained through a DataSource.

[1]Getting a DataSource from JNDI:
In this case, we use the JndiObjectFactoryBean.

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
 <property name="jndiName">
  <value>java:comp/env/jdbc/myDatasource</value>
 </property>
</bean>

[2]Creating a DataSource connection pool:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driver">
<value>${db.driver}</value>
</property>
<property name="url">
<value>${db.url}</value>
</property>
<property name="username">
<value>${db.username}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
</bean>

ManagerDataSource. This class can easily be configured and used with a unit test or suite of unit tests.
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);

Spring separates the fixed and variant parts of the data access process into two distinct classes: templates and callbacks. Templates manage the fixed part of the process while callbacks are where you fill in the implementation details.

Using JDBC with Spring:
Using JdbcTemplate:

public class StudentDaoJdbc implements StudentDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

}

<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource"><ref bean="dataSource"/></property>
</bean>
<bean id="studentDao" class="StudentDaoJdbc">
<property name="jdbcTemplate"><ref bean="jdbcTemplate"/></property>
</bean>
<bean id="courseDao" class="CourseDaoJdbc">
<property name="jdbcTemplate"><ref bean="jdbcTemplate"/></property>
</bean>


The first callback we will explore is PreparedStatementCreator.
PreparedStatement createPreparedStatement(Connection conn) throws SQLException;
When you implement this interface, you are responsible for creating and returning a PreparedStatement from the Connection argument

你可能感兴趣的:(spring)