Spring DAO之JDBC
Spring提供的DAO(數據訪問對象)支持主要的目的是便於以標准的方式使用不同的數據訪問技術
為了便於以一種一致的方式使用各種數據訪問技術
Dao支持類
JdbcDaoSupport
HibernateDaoSupport
JdoDaoSupport
JpaDaoSupport
本節主要討論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) {
this
}
public String getName() {
return name;
}
public void setName(String name) {
this
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this
}
}
/**
* Created by IntelliJ IDEA
* <b>User</b>: leizhimin<br>
* <b>Date</b>:
* <b>Note</b>: DAO接口
*/
public interface IUserDAO {
public void insert(User user);
public User find(Integer id);
}
import javax
import java
import java
/**
* Created by IntelliJ IDEA
* <b>User</b>: leizhimin<br>
* <b>Date</b>:
* <b>Note</b>: 基類DAO
*/
public class BaseDAO {
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this
}
public Connection getConnection() {
Connection conn = null;
try {
conn = dataSource
} catch (SQLException e) {
e
}
return conn;
}
}
/**
* Created by IntelliJ IDEA
* <b>User</b>: leizhimin<br>
* <b>Date</b>:
* <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 = user
int age = user
// jdbcTemplate
// +
String sql =
getJdbcTemplate()
}
public User find(Integer id) {
List rows = getJdbcTemplate()
Iterator it = erator();
if (it
Map userMap = (Map) it
Integer i = new Integer(userMap
String name = userMap
Integer age = new Integer(userMap
User user = new User();
user
user
user
return user;
}
return null;
}
}
<?xml version=
<!DOCTYPE beans PUBLIC
<beans>
<bean id=
class=
<property name=
<value>com
</property>
<property name=
<value>jdbc:mysql://localhost:
</property>
<property name=
<value>root</value>
</property>
<property name=
<value>leizhimin</value>
</property>
</bean>
<bean id=
<property name=
<ref bean=
</property>
</bean>
<bean id=
class=
</bean>
</beans>
import orgntext
import orgntext
/**
* Created by IntelliJ IDEA
* <b>User</b>: leizhimin<br>
* <b>Date</b>:
* <b>Note</b>: 測試類
*/
public class SpringDAODemo {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext(
User user = new User();
user
user
IUserDAO userDAO = (IUserDAO) context
userDAO
user = userDAO
System
}
}
運行結果
log
log
name: jdbctemplate
Process finished with exit code
From:http://tw.wingwit.com/Article/program/Java/ky/201311/28510.html