---
title: "《研磨struts2》第十二章 CRUD综合运用 之 12.2 实现域对象和数据层"
author: "研磨struts2"
date: "2012-05-28T07:53:45Z"
tags: []
categories: ["企业架构"]
slug: "struts2-crud-12-2"
draft: false
lastmod: "2012-05-28T07:53:45Z"
id: 1542398
url: "https://rubbing-struts2.iteye.com/blog/1542398"
---

## 12.2  实现域对象和数据层

### []()12.2.1  建表和域对象

在示例中只需要管理用户的基本信息，用户编号（userId）、姓名（name）、性别（sex）、年龄（age）即可，在mysql中，可以用下面的语句建表：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4110.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4110.html)[打印](http://sishuok.com/forum/blogPost/list/4110.html)

1. create table tbl\_user(
2. userId int primary key,
3. name varchar(20),
4. sex varchar(10),
5. age int
6. ) character set =gb2312;

在上面的语句中，建立了一张表叫tbl\_user，分别有4个字段：

- userId：整数类型，是这张表的主键。
- name：字符类型。注意：varchar后面的20表示这个字段最大可以接受20个字节。
- sex：字符类型。
- age：整数类型。

建表语句后面的“character set =gb2312”，是用来设置该表的字符集，使其能够支持中文，跟在后面连接数据库连接语句里面设置的字符集相对应。

建表之后，就可以建立与它相对应的域对象了。在建立域对象的时候，通常的实现方式是：表对应域对象的类，表的每个字段对应类中的一个属性并且为这个属性配备相应的getter/setter方法，表中的主键字段要用来生成hashCode方法和equals方法。域对象的示例代码为：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4110.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4110.html)[打印](http://sishuok.com/forum/blogPost/list/4110.html)

01. public class UserModel {
02. private int userId;
03. private String name;
04. private String sex;
05. private int age;
06. public int getUserId() {
07. return userId;
08. }
09. public void setUserId(int userId) {
10. this.userId = userId;
11. }
12. public String getName() {
13. return name;
14. }
15. public void setName(String name) {
16. this.name = name;
17. }
18. public String getSex() {
19. return sex;
20. }
21. public void setSex(String sex) {
22. this.sex = sex;
23. }
24. public int getAge() {
25. return age;
26. }
27. public void setAge(int age) {
28. this.age = age;
29. }
30. public int hashCode() {
31. final int prime = 31;
32. int result = 1;
33. result = prime * result + userId;
34. return result;
35. }
36. public boolean equals(Object obj) {
37. if (this == obj)
38. return true;
39. if (obj == null)
40. return false;
41. if (getClass() != obj.getClass())
42. return false;
43. final UserModel other = (UserModel) obj;
44. if (userId != other.userId)
45. return false;
46. return true;
47. }
48. }

### []()12.2.2  建立条件组合对象

在查询的时候，通常需要实现用户可以自由组合查询条件的功呢，也就是用户自由组合使用多个查询条件中的一项或某几项。

比如，在查询用户信息的时候，可以指定如下查询条件：按照用户编号精确查询；按照姓名模糊查询（输入“李”可以查出所有名字中带有“李”字的用户）；按性别精确查询；按年龄的范围查询，如15到20之间，或者大于25岁的。

这些条件用户可能都填了，也可能只填其中的某几项，也可能都不填写。那么在做查询的时候，就要去处理用户填写条件的各种组合情况，并把那些符合所有这些条件的记录查询出来。

先不要着急想怎么实现组合查询，第一个问题是用一个什么样的对象来存放这样一组条件呢？

按照上面描述的组合条件，这个对象要包含一个编号（用于精确查询）、一个姓名（用于模糊查询）、一个性别（用于模糊查询）和两个年龄（一个用于存范围的最大值，另一个用于存范围的最小值）。有朋友马上就想到了使用UserModel，但是这里有一个小小的问题，UserModel可以存一个编号、一个姓名、一个性别和一个年龄，可是还少一个年龄属性。

可以简单的如下来实现，做一个UserQueryModel，让它继承UserModel，在UserQueryModel中只写出UserModel缺少的属性（一个年龄），当然它的名字不能叫age，可以叫做age2，这样在查询的时候就使用UserQueryModel，示例代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4110.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4110.html)[打印](http://sishuok.com/forum/blogPost/list/4110.html)

1. public class UserQueryModel extends UserModel {
2. private int age2;
3. public int getAge2() {
4. return age2;
5. }
6. public void setAge2(int age2) {
7. this.age2 = age2;
8. }
9. }

### []()12.2.3  实现数据层

使用JDBC作为这次示例的数据层，但是JDBC并不是本书的介绍重点。因此，这里只是简单的给出其实现，如果读者没有JDBC基础，请查阅JDBC的相关资料。

       为了实现最终的增删改查的目标，数据层必须实现以下功能：

- 增：添加一条新的记录。
- 改：按照主键修改一条已有记录。
- 删：按照主键删除一条已有记录。
- 查一条：按照主键查询出一条已有记录。
- 查全部：查出所有已有记录。
- 按条件查：按照组合条件查出所有符合条件的记录。

要实现数据层首先就要获得数据库的连接，这里用的是apache的简单数据源BasicDataSource实现，只需要指定驱动类、数据库的地址、用户名和密码即可，最终返回一个DataSource对象，示例代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4110.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4110.html)[打印](http://sishuok.com/forum/blogPost/list/4110.html)

01. public class DataSourceHolder {
02. private BasicDataSource ds = new BasicDataSource();
03. private DataSourceHolder(){
04. ds.setDriverClassName("org.gjt.mm.mysql.Driver");
05. ds.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gb2312");
06. ds.setUsername("root");
07. ds.setPassword("");
08. }
09. private static class SingletonHolder{
10. private static DataSourceHolder instance = new DataSourceHolder();
11. }
12. public static  DataSourceHolder getInstance(){
13. return SingletonHolder.instance;
14. }
15. public  DataSource getDataSource(){
16. return ds;
17. }
18. }

上面的DataSourceHolder实现成了一个单例，这里用的是“Lazy initialization holder class模式”来实现的单例，不了解的朋友可以参见拙著《研磨设计模式》的单例模式一章，或者是参阅其他的相关资料。

接下来，开始正式实现数据层的各个方法：

1：实现添加一条新的记录，示例代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4110.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4110.html)[打印](http://sishuok.com/forum/blogPost/list/4110.html)

01. public void create(UserModel user){
02. Connection conn = null;
03. try {
04. conn = DataSourceHolder.getInstance().getDataSource().getConnection();
05. final String sql = "insert into tbl\_user(userId,name,sex,age) values(?,?,?,?)";
06. PreparedStatement ps = conn.prepareStatement(sql);
07. int count = 1;
08. ps.setInt(count++, user.getUserId());
09. ps.setString(count++, user.getName());
10. ps.setString(count++, user.getSex());
11. ps.setInt(count++, user.getAge());
12. ps.execute();
13. ps.close();
14. } catch (Exception e) {
15. e.printStackTrace();
16. } finally {
17. try {
18. conn.close();
19. } catch (SQLException e) {
20. e.printStackTrace();
21. }
22. }
23. }

2：实现按照主键修改一条已有记录，示例代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4110.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4110.html)[打印](http://sishuok.com/forum/blogPost/list/4110.html)

01. public void update(UserModel user){
02. Connection conn = null;
03. try {
04. conn = DataSourceHolder.getInstance().getDataSource().getConnection();
05. final String sql = "update tbl\_user set name=?,sex=?,age=? where userId=?";
06. PreparedStatement ps = conn.prepareStatement(sql);
07. int count = 1;
08. ps.setString(count++, user.getName());
09. ps.setString(count++, user.getSex());
10. ps.setInt(count++, user.getAge());
11. ps.setInt(count++, user.getUserId());
12. ps.execute();
13. ps.close();
14. } catch (Exception e) {
15. e.printStackTrace();
16. } finally {
17. try {
18. conn.close();
19. } catch (SQLException e) {
20. e.printStackTrace();
21. }
22. }
23. }

3：实现按照主键删除一条已有记录，示例代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4110.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4110.html)[打印](http://sishuok.com/forum/blogPost/list/4110.html)

01. public void delete(int userId){
02. Connection conn = null;
03. try {
04. conn = DataSourceHolder.getInstance().getDataSource().getConnection();
05. final String sql = "delete from tbl\_user where userId=?";
06. PreparedStatement ps = conn.prepareStatement(sql);
07. ps.setInt(1, userId);
08. ps.execute();
09. ps.close();
10. } catch (Exception e) {
11. e.printStackTrace();
12. } finally {
13. try {
14. conn.close();
15. } catch (SQLException e) {
16. e.printStackTrace();
17. }
18. }
19. }

4：事先按照主键查询出一条已有记录的功能，示例代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4110.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4110.html)[打印](http://sishuok.com/forum/blogPost/list/4110.html)

01. public UserModel getSingle(int userId){
02. UserModel user = null;
03. Connection conn = null;
04. try {
05. conn = DataSourceHolder.getInstance().getDataSource().getConnection();
06. final String sql = "select * from tbl\_user where userId=?";
07. PreparedStatement ps = conn.prepareStatement(sql);
08. ps.setInt(1, userId);
09. ResultSet rs = ps.executeQuery();
10. if(rs.next()){
11. user = this.rs2model(rs);
12. }
13. rs.close();
14. ps.close();
15. } catch (Exception e) {
16. e.printStackTrace();
17. } finally {
18. try {
19. conn.close();
20. } catch (SQLException e) {
21. e.printStackTrace();
22. }
23. }
24. return user;
25. }
26. private UserModel rs2model(ResultSet rs) throws Exception{
27. UserModel user = new UserModel();
28. user.setUserId(rs.getInt("userId"));
29. user.setName(rs.getString("name"));
30. user.setSex(rs.getString("sex"));
31. user.setAge(rs.getInt("age"));
32. return user;
33. }

在里面实现了一个私有方法rs2model，用来把从数据库获取的一条记录，转换成为一个UserModel的对象。这是个多个方法公用的方法，因此把这些公共的功能提出来实现成为私有方法。

5：实现查出所有已有记录的功能，示例如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4110.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4110.html)[打印](http://sishuok.com/forum/blogPost/list/4110.html)

01. public List&lt;UserModel&gt; getAll(){
02. List&lt;UserModel&gt; list = new ArrayList&lt;UserModel&gt;();
03. Connection conn = null;
04. try {
05. conn = DataSourceHolder.getInstance().getDataSource().getConnection();
06. final String sql = "select * from tbl\_user order by userId";
07. PreparedStatement ps = conn.prepareStatement(sql);
08. ResultSet rs = ps.executeQuery();
09. while (rs.next()){
10. UserModel user = this.rs2model( rs);
11. list.add(user);
12. }
13. rs.close();
14. ps.close();
15. } catch (Exception e) {
16. e.printStackTrace();
17. } finally {
18. try {
19. conn.close();
20. } catch (SQLException e) {
21. e.printStackTrace();
22. }
23. }
24. return list;
25. }

6：实现按照组合条件查出所有符合条件的记录。实现这个功能会稍微麻烦一点，首要的问题就是用户输入的条件是不确定的，因此查询用的sql也就不能确定了，那么怎么实现呢？

方法是动态的拼接sql，根据用户输入的条件来拼接sql，如果用户输入了某个条件值，那么就在sql上拼接该条件，如果用户没有输入，那么就不用在sql上拼接这个条件。具体的实现请参看generateWhere方法。示例代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4110.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4110.html)[打印](http://sishuok.com/forum/blogPost/list/4110.html)

01. /\**
02. * 根据UserQueryModel中的数据情况动态生成对应的条件语句
03. * @param uqm 封装查询条件数据的模型
04. * @return 按照查询条件数据来动态生成的条件语句
05. \*/
06. private String generateWhere(UserQueryModel uqm){
07. StringBuffer buffer = new StringBuffer();
08. //用户是否选用用户编号作为条件
09. if (uqm.getUserId()&gt;0){
10. buffer.append(" and userId = ?");
11. }
12. //用户是否选用用户姓名作为条件
13. if (uqm.getName()!=null&&uqm.getName().trim().length()&gt;0){
14. buffer.append(" and name like ?");
15. }
16. //用户是否选用性别作为条件
17. if (uqm.getSex()!=null&&uqm.getSex().trim().length()&gt;0){
18. buffer.append(" and sex = ?");
19. }
20. //用户是否选用年龄范围最小值作为条件
21. if (uqm.getAge()&gt;0){
22. buffer.append(" and age &gt;= ?");
23. }
24. //用户是否选用年龄范围最大值作为条件
25. if (uqm.getAge2()&gt;0){
26. buffer.append(" and age &lt;= ?");
27. }
28. return buffer.toString();
29. }

另外一个问题，由于sql是动态拼接出来的，那么向sql传入参数的过程也不能固定，同样按照动态拼接sql的方式，来动态的设置sql的参数。具体的实现请参看preparePs方法。示例代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4110.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4110.html)[打印](http://sishuok.com/forum/blogPost/list/4110.html)

01. /\**
02. * 向sql语句中的"?" 设置参数值
03. * @param uqm 封装查询条件数据的模型
04. * @param ps PreparedStatement 对象
05. \*/
06. private void preparePs(UserQueryModel uqm,PreparedStatement ps) throws SQLException{
07. int count = 1;
08. if (uqm.getUserId()&gt;0){
09. ps.setInt(count++, uqm.getUserId());
10. }
11. if (uqm.getName()!=null&&uqm.getName().trim().length()&gt;0){
12. ps.setString(count++, "%"+uqm.getName()+"%");
13. }
14. if (uqm.getSex()!=null&&uqm.getSex().trim().length()&gt;0){
15. ps.setString(count++, uqm.getSex());
16. }
17. if (uqm.getAge()&gt;0){
18. ps.setInt(count++, uqm.getAge());
19. }
20. if (uqm.getAge2()&gt;0){
21. ps.setInt(count++, uqm.getAge2());
22. }
23. }

再来看看按条件查询功能的实现，示例代码如下：

 

java代码：

[查看](http://sishuok.com/forum/blogPost/list/4110.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/4110.html)[打印](http://sishuok.com/forum/blogPost/list/4110.html)

01. public List&lt;UserModel&gt; getByCondition(UserQueryModel uqm){
02. List&lt;UserModel&gt; list = new ArrayList&lt;UserModel&gt;();
03. Connection conn = null;
04. try {
05. conn = DataSourceHolder.getInstance().getDataSource().getConnection();
06. //调用前面定义的生成where语句的方法
07. //由于不知道UserQueryModel中属性值的情况
08. //所以必须在sql语句的主题中添上恒成立条件1=1
09. final String sql = "select * from tbl\_user where 1=1 " + this.generateWhere(uqm) + " order by userId";
10. PreparedStatement ps = conn.prepareStatement(sql);
11. //调用前面定义的向PrepareStatment赋值的方法
12. this.preparePs(uqm, ps);
13. ResultSet rs = ps.executeQuery();
14. while (rs.next()){
15. UserModel user = this.rs2model(rs);
16. list.add(user);
17. }
18. rs.close();
19. ps.close();
20. } catch (Exception e) {
21. e.printStackTrace();
22. } finally {
23. try {
24. conn.close();
25. } catch (SQLException e) {
26. e.printStackTrace();
27. }
28. }
29. return list;
30. }

 

私塾在线网站原创《[研磨struts2](http://sishuok.com/forum/blogCategory/showByCategory.html?categories_id=81&user_id=5948)》系列

转自请注明出处：【[http://sishuok.com/forum/blogPost/list/0/4101.html](http://sishuok.com/forum/blogPost/list/0/4101.html)】

欢迎访问[http://sishuok.com](http://sishuok.com/)获取更多内容