这里将用到以下几个包:
aopalliance-1.0.jar
commons-collections.jar
commons-dbcp.jar
commons-logging-1.1.1.jar
commons-pool.jar
jstl.jar
log4j-1.2.15.jar
mysql-connector-java-5.1.6-bin.jar
spring-beans-2.5.6.jar
spring-context-2.5.6.jar
spring-context-support-2.5.6.jar
spring-core-2.5.6.jar
spring-jdbc-2.5.6.jar
spring-tx-2.5.6.jar
spring-web-2.5.6.jar
spring-webmvc-2.5.6.jar
standard.jar
主要增加了commons-collections.jar、commons-dbcp.jar、commons-pool.jar、mysql-connector-java-5.1.6-bin.jar和spring-jdbc-2.5.6.jar
先弄个数据库,这里使用MySQL,我的最爱! 可惜前途未卜!
建库:
- CREATE DATABASE `spring` /*!40100 DEFAULT CHARACTER SET utf8 */;
CREATE DATABASE `spring` /*!40100 DEFAULT CHARACTER SET utf8 */;
建表:
- DROP TABLE IF EXISTS `spring`.`account`;
- CREATE TABLE `spring`.`account` (
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `username` varchar(45) NOT NULL,
- `password` varchar(45) NOT NULL,
- `birthday` datetime NOT NULL,
- `email` varchar(45) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `spring`.`account`;
CREATE TABLE `spring`.`account` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`birthday` datetime NOT NULL,
`email` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
插入默认数据:
- INSERT INTO `spring`.`account`(
- `username`,
- `password`,
- `birthday`,
- `email`)
- VALUES(
- 'snowolf',
- 'zlex',
- '2010-01-01',
- 'snowolf@zlex.org');
INSERT INTO `spring`.`account`(
`username`,
`password`,
`birthday`,
`email`)
VALUES(
'snowolf',
'zlex',
'2010-01-01',
'snowolf@zlex.org');
给出一个数据库查询的结果:
很不巧,为了能让数据查询更有意义,我又要改动Account类:
Account.java
- public class Account implements Serializable {
- /**
- * 主键
- */
- private int id;
- /**
- * 用户名
- */
- private String username;
- /**
- * 密码
- */
- private String password;
- /**
- * 生日
- */
- private Date birthday;
- /**
- */
- private String email;
- // get方法set方法省略
- }
public class Account implements Serializable {
/**
* 主键
*/
private int id;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 生日
*/
private Date birthday;
/**
* Email
*/
private String email;
// get方法set方法省略
}
这样,域对象与数据库表将完成一一对应绑定关系。
再建立一个用于构建数据源配置的文件database.properties
database.properties:
- dataSource.driverClassName=com.mysql.jdbc.Driver
- dataSource.url=jdbc:mysql://localhost:3306/spring
- dataSource.username=root
- dataSource.password=admin
- dataSource.maxActive=200
- dataSource.maxIdle=50
- dataSource.maxWait=10000
dataSource.driverClassName=com.mysql.jdbc.Driver dataSource.url=jdbc:mysql://localhost:3306/spring dataSource.username=root dataSource.password=admin dataSource.maxActive=200 dataSource.maxIdle=50 dataSource.maxWait=10000
该文件位于/WEB-INF/目录下。
接下来,我们需要把它引入spring容器,修改applicationContext.xml:
applicationContext.xml
- <context:property-placeholder
- location="/WEB-INF/database.properties" />
<context:property-placeholder location="/WEB-INF/database.properties" />
如果需要引入多个properties文件,可以用逗号分隔。
这时,我们已经引入了数据源配置,我们可以通过修改dao.xml构建基于DBCP的数据源:
dao.xml中dataSource配置
- <bean
- id="dataSource"
- class="org.apache.commons.dbcp.BasicDataSource"
- destroy-method="close"
- lazy-init="false"
- p:driverClassName="${dataSource.driverClassName}"
- p:url="${dataSource.url}"
- p:username="${dataSource.username}"
- p:password="${dataSource.password}"
- p:maxActive="${dataSource.maxActive}"
- p:maxIdle="${dataSource.maxIdle}"
- p:maxWait="${dataSource.maxWait}" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" lazy-init="false" p:driverClassName="${dataSource.driverClassName}" p:url="${dataSource.url}" p:username="${dataSource.username}" p:password="${dataSource.password}" p:maxActive="${dataSource.maxActive}" p:maxIdle="${dataSource.maxIdle}" p:maxWait="${dataSource.maxWait}" />
上述配置稀松平常,没有什么好阐述的内容,这与一般spring配置无异样。
需要注意的是这个jdbcTemplate配置!
dao.xml中jdbcTemplate配置
- <bean
- class="org.springframework.jdbc.core.JdbcTemplate"
- p:dataSource-ref="dataSource" />
<bean class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource" />
这个配置很关键,如果你要使用其他的ORM框架,同样需要配置这样的模板类,在Dao实现中无需继承JdbcDaoSupport类。
不需要明确JdbcTemplate的id(id="jdbcTemplate")吗?不再需要了!
AccountDao.java
- public interface AccountDao {
- /**
- * 读取账户信息
- *
- * @param username
- * @return
- */
- Account read(String username);
- /**
- * 读取账户信息
- *
- * @param id
- * @return
- */
- Account read(int id);
- }
public interface AccountDao {
/**
* 读取账户信息
*
* @param username
* @return
*/
Account read(String username);
/**
* 读取账户信息
*
* @param id
* @return
*/
Account read(int id);
}
AccountDaoImpl.java
- /**
- * 2010-1-23
- */
- package org.zlex.spring.dao.impl;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.jdbc.core.JdbcTemplate;
- import org.springframework.jdbc.core.RowMapper;
- import org.springframework.stereotype.Repository;
- import org.zlex.spring.dao.AccountDao;
- import org.zlex.spring.domain.Account;
- /**
- * 账户数据库实现
- *
- * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a>
- * @version 1.0
- * @since 1.0
- */
- @Repository
- public class AccountDaoImpl implements AccountDao {
- @Autowired
- private JdbcTemplate jdbcTemplate;
- @Override
- public Account read(String username) {
- String sql = "SELECT * From account WHERE username = ?";
- return (Account) jdbcTemplate.queryForObject(sql,
- new Object[] { username }, accountRowMap);
- }
- @Override
- public Account read(int id) {
- String sql = "SELECT * From account WHERE id = ?";
- return (Account) jdbcTemplate.queryForObject(sql, new Object[] { id },
- accountRowMap);
- }
- protected RowMapper accountRowMap = new RowMapper() {
- @Override
- public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
- Account account = new Account();
- account.setId(rs.getInt("id"));
- account.setUsername(rs.getString("username"));
- account.setPassword(rs.getString("password"));
- account.setBirthday(rs.getDate("birthday"));
- account.setEmail(rs.getString("email"));
- return account;
- }
- };
- }
/**
* 2010-1-23
*/
package org.zlex.spring.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.zlex.spring.dao.AccountDao;
import org.zlex.spring.domain.Account;
/**
* 账户数据库实现
*
* @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a>
* @version 1.0
* @since 1.0
*/
@Repository
public class AccountDaoImpl implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Account read(String username) {
String sql = "SELECT * From account WHERE username = ?";
return (Account) jdbcTemplate.queryForObject(sql,
new Object[] { username }, accountRowMap);
}
@Override
public Account read(int id) {
String sql = "SELECT * From account WHERE id = ?";
return (Account) jdbcTemplate.queryForObject(sql, new Object[] { id },
accountRowMap);
}
protected RowMapper accountRowMap = new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setId(rs.getInt("id"));
account.setUsername(rs.getString("username"));
account.setPassword(rs.getString("password"));
account.setBirthday(rs.getDate("birthday"));
account.setEmail(rs.getString("email"));
return account;
}
};
}
分段详述:
注解@Repository明确这个类是用于持久层的实现类,注意这样的注解不能用于接口,仅适用于实现类!
同时,不再需要继承JdbcDaoSupport类,其而代之的是直接注入JdbcTemplate类!
再看声明JdbcTemplate类:
- @Autowired
- private JdbcTemplate jdbcTemplate;
@Autowired
private JdbcTemplate jdbcTemplate;
需要说明一下,这里的JdbcTemplate对象jdbcTemplate名称可以自定,没有任何限制!
这里使用 RowMapper 定义了一个用于绑定Account域对象的内部映射类:
RowMapper
- protected RowMapper accountRowMap = new RowMapper() {
- @Override
- public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
- Account account = new Account();
- account.setId(rs.getInt("id"));
- account.setUsername(rs.getString("username"));
- account.setPassword(rs.getString("password"));
- account.setBirthday(rs.getDate("birthday"));
- account.setEmail(rs.getString("email"));
- return account;
- }
- };
protected RowMapper accountRowMap = new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setId(rs.getInt("id"));
account.setUsername(rs.getString("username"));
account.setPassword(rs.getString("password"));
account.setBirthday(rs.getDate("birthday"));
account.setEmail(rs.getString("email"));
return account;
}
};
语句级的内容,十分简单,如下所示:
- @Override
- public Account read(String username) {
- String sql = "SELECT * From account WHERE username = ?";
- return (Account) jdbcTemplate.queryForObject(sql,
- new Object[] { username }, accountRowMap);
- }
- @Override
- public Account read(int id) {
- String sql = "SELECT * From account WHERE id = ?";
- return (Account) jdbcTemplate.queryForObject(sql, new Object[] { id },
- accountRowMap);
- }
@Override
public Account read(String username) {
String sql = "SELECT * From account WHERE username = ?";
return (Account) jdbcTemplate.queryForObject(sql,
new Object[] { username }, accountRowMap);
}
@Override
public Account read(int id) {
String sql = "SELECT * From account WHERE id = ?";
return (Account) jdbcTemplate.queryForObject(sql, new Object[] { id },
accountRowMap);
}
写完这两段代码不由感慨,我曾经就这么噼里啪啦的敲了一年多这样的代码。不断的做绑定、映射、写SQL,直到可以有机会将持久层JDBC实现替换Hibernate、iBatis,我才得以解放!
接着,再调整一下Service实现类
AccountServiceImpl.java
- public class AccountServiceImpl implements AccountService {
- @Autowired
- private AccountDao accountDao;
- @Override
- public Account read(String username, String password) {
- Account account = accountDao.read(username);
- if (!password.equals(account.getPassword())) {
- account = null;
- }
- return account;
- }
- @Override
- public Account read(int id) {
- return accountDao.read(id);
- }
- }
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public Account read(String username, String password) {
Account account = accountDao.read(username);
if (!password.equals(account.getPassword())) {
account = null;
}
return account;
}
@Override
public Account read(int id) {
return accountDao.read(id);
}
}
使用AccountDao接口来完成响应的操作,逻辑部分不做详述,根据业务逻辑而定!
稍稍修改一下profile.jsp,将用户的生日、邮件地址都输出出来!
- <fieldset><legend>用户信息</legend>
- <ul>
- <li><label>用户名:</label><c:out value="${account.username}" /></li>
- <li><label>生日:</label><fmt:formatDate value="${account.birthday}"
- pattern="yyyy年MM月dd日" /></li>
- <li><label>Email:</label><c:out value="${account.email}" /></li>
- </ul>
- </fieldset>
- 标签<fmt:formatDate />用于格式化输出,大家可以了解一下,很简单很好用的标签! :D
<fieldset><legend>用户信息</legend> <ul> <li><label>用户名:</label><c:out value="${account.username}" /></li> <li><label>生日:</label><fmt:formatDate value="${account.birthday}" pattern="yyyy年MM月dd日" /></li> <li><label>Email:</label><c:out value="${account.email}" /></li> </ul> </fieldset> 标签<fmt:formatDate />用于格式化输出,大家可以了解一下,很简单很好用的标签! :D
启动应用,登录,查看用户信息: