Spring DAO之JDBC
Spring提供的DAO(数据访问对象)支持主要的目的是便于以标准的方式使用不同的数据访问技术 如JDBCHibernate或者JDO等它不仅可以让你方便地在这些持久化技术间切换 而且让你在编码的时候不用考虑处理各种技术中特定的异常
为了便于以一种一致的方式使用各种数据访问技术如JDBCJDO和Hibernate Spring提供了一套抽象DAO类供你扩展这些抽象类提供了一些方法通过它们你可以 获得与你当前使用的数据访问技术相关的数据源和其他配置信息
Dao支持类
JdbcDaoSupport JDBC数据访问对象的基类 需要一个DataSource同时为子类提供 JdbcTemplate
HibernateDaoSupport Hibernate数据访问对象的基类 需要一个SessionFactory同时为子类提供 HibernateTemplate也可以选择直接通过 提供一个HibernateTemplate来初始化 这样就可以重用后者的设置例如SessionFactory flush模式异常翻译器(exception translator)等等
JdoDaoSupport JDO数据访问对象的基类 需要设置一个PersistenceManagerFactory 同时为子类提供JdoTemplate
JpaDaoSupport JPA数据访问对象的基类 需要一个EntityManagerFactory同时 为子类提供JpaTemplate
本节主要讨论Sping对JdbcDaoSupport的支持
下面是个例子
drop table if exists user;
/* Table: user
create table user
(
id bigint AUTO_INCREMENT not null
name varchar()
age int
primary key (id)
);
public class User {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
thisid = id;
}
public String getName() {
return name;
}
public void setName(String name) {
thisname = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
thisage = age;
}
}
/**
* Created by IntelliJ IDEA<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: ::<br>
* <b>Note</b>: DAO接口
*/
public interface IUserDAO {
public void insert(User user);
public User find(Integer id);
}
import javaxsqlDataSource;
import javasqlConnection;
import javasqlSQLException;
/**
* Created by IntelliJ IDEA<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: ::<br>
* <b>Note</b>: 基类DAO提供了数据源注入
*/
public class BaseDAO {
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
thisdataSource = dataSource;
}
public Connection getConnection() {
Connection conn = null;
try {
conn = dataSourcegetConnection();
} catch (SQLException e) {
eprintStackTrace();
}
return conn;
}
}
/**
* Created by IntelliJ IDEA<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: ::<br>
* <b>Note</b>: DAO实现
*/
public class UserDAO extends BaseDAO implements IUserDAO {
public JdbcTemplate getJdbcTemplate(){
return new JdbcTemplate(getDataSource());
}
public void insert(User user) {
String name = usergetName();
int age = usergetAge()intValue();
// jdbcTemplateupdate(INSERT INTO user (nameage)
// + VALUES( + name + + age + ));
String sql = insert into user(nameage) values(??);
getJdbcTemplate()update(sqlnew Object[]{nameage});
}
public User find(Integer id) {
List rows = getJdbcTemplate()queryForList(
SELECT * FROM user WHERE id= + idintValue());
Iterator it = erator();
if (ithasNext()) {
Map userMap = (Map) itnext();
Integer i = new Integer(userMapget(id)toString());
String name = userMapget(name)toString();
Integer age = new Integer(userMapget(age)toString());
User user = new User();
usersetId(i);
usersetName(name);
usersetAge(age);
return user;
}
return null;
}
}
<?xml version= encoding=UTF?>
<!DOCTYPE beans PUBLIC //SPRING/DTD BEAN/EN
beansdtd>
<beans>
<bean id=dataSource
class=monsdbcpBasicDataSource singleton=true>
<property name=driverClassName>
<value>commysqljdbcDriver</value>
</property>
<property name=url>
<value>jdbc:mysql://localhost:/springdb</value>
</property>
<property name=username>
<value>root</value>
</property>
<property name=password>
<value>leizhimin</value>
</property>
</bean>
<bean id=baseDAO class=comlavasoftspringnotech_jdbc_tempBaseDAO abstract=true>
<property name=dataSource>
<ref bean=dataSource/>
</property>
</bean>
<bean id=userDAO
class=comlavasoftspringnotech_jdbc_tempUserDAO parent=baseDAO>
</bean>
</beans>
import orgntextApplicationContext;
import orgntextsupportFileSystemXmlApplicationContext;
/**
* Created by IntelliJ IDEA<br>
* <b>User</b>: leizhimin<br>
* <b>Date</b>: ::<br>
* <b>Note</b>: 测试类客户端
*/
public class SpringDAODemo {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext(D:\\_spring\\src\\com\\lavasoft\\springnote\\ch_jdbc_temp\\beanjdbctempxml);
User user = new User();
usersetName(hahhahah);
usersetAge(new Integer());
IUserDAO userDAO = (IUserDAO) contextgetBean(userDAO);
userDAOinsert(user);
user = userDAOfind(new Integer());
Systemoutprintln(name: + usergetName());
}
}
运行结果
logj:WARN No appenders could be found for logger (orgreCollectionFactory)
logj:WARN Please initialize the logj system properly
name: jdbctemplate
Process finished with exit code