forhd
handong890
2011-01-28 11:27

对充血模型的疑问

  • 领域模型

小弟我在坛子上看到关于贫血模型和充血模型的讨论后一直再想这对于我这种代码小工意味着啥?
是否可以更快更迅速更敏捷的完成代码完成开发。
一直做的项目都是SSH 然后分层 action,service,dao,entity;有时候我觉得dao层没什么必要啊,既然
hibernate是面向对象为何还要 dao.save(entity)   dao.update(entity) 这样操作?
感觉如果去掉dao层 直接entity.update(),entity.delete();  这样是否会更形象?
然后小弟开始尝试,首先搭了个struts2+spring3+Hibernate3.6的ssh工程用的是全注解搭法这样开发就不用写配置文件了还是相当的爽啊

首先我觉得应该有一个公共的类充当所有entity的父类


import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

@Repository("MagicH")
public class MagicH extends HibernateTemplate {

@Resource(name = "sessionFactory")
public void setSuperSessionFactory(SessionFactory sessionFactory) {
    super.setSessionFactory(sessionFactory);
}

private Serializable id; // 标示
private Class clazz; // 实体
private Object entity; // 数据库实体
private PropertyDescriptor targetPds[];  //初始化后属性
private HashMap setMethodMap = new HashMap();   //set方法映射
private HashMap getMethodMap = new HashMap();  //get方法映射

/**
 * 模型初始化
 * 
 * @param clazz
 * @param id
 */
public boolean init(Class clazz, Serializable id) {
    this.id = id;
    this.clazz = clazz;
    PropertyDescriptor targetPds[] = BeanUtils.getPropertyDescriptors(clazz); 
      for (PropertyDescriptor pdObj : targetPds)
        {
           setMethodMap.put(pdObj.getName().toLowerCase(), pdObj.getWriteMethod());
           getMethodMap.put(pdObj.getName().toLowerCase(), pdObj.getReadMethod());
        }
      this.entity = get(clazz, id);
    return this.entity==null?false:true;  
}

/**
 * 获取对象实体
 * 
 * @return
 */
public Object getObj() {
    if (entity == null) {
        this.entity = get(clazz, id);
    }
    return entity;
}

/**
 * 删除对象实体
 */
public void delObj() {
    if (entity != null)
        delete(entity);
    else
        delete(get(clazz, id));
}

/**
 * 设置数据库实体属性
 * @param propertyName
 * @param propertyValue
 */
public void setProperty(String propertyName, Object propertyValue) {

      Method writeMethod = (Method) setMethodMap.get(propertyName.toLowerCase());
      try {
        writeMethod.invoke(entity, new Object[] {propertyValue});
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

/**
 * 获取属性的值
 * @param propertyName
 * @return
 */
public Object getPropertyValue(String propertyName)
{
    Method readMethod = (Method)getMethodMap.get(propertyName.toLowerCase());
    Object returnValue = null;
    try {
        returnValue = readMethod.invoke(entity,null);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return returnValue;
}
/**
 * 更新对象
 */
public void updateObj()
{
    update(entity);
}


/**
 * 保存对象
 * @param obj
 * @return
 */
public Serializable addObj(Object obj)
{
    Serializable id =  save(obj);
    init(obj.getClass(),id);
    return  id;
}

}



建立一张用户表测试,对应实体如下

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.stereotype.Repository;

import com.usoft.core.dao.impl.MagicH;

/**

  • MagicUser entity. @author MyEclipse Persistence Tools
    */
    @Repository("MagicUser")
    @Entity
    @Table(name = "MAGIC_USER")
    public class MagicUser extends MagicH implements java.io.Serializable {

    // Fields

    private String userId;
    private String userNam;
    private String userSex;
    private String userPhone;

    // Constructors

    /** default constructor */
    public MagicUser() {
    }

    /** full constructor */
    public MagicUser(String userNam, String userSex, String userPhone) {
    this.userNam = userNam;
    this.userSex = userSex;
    this.userPhone = userPhone;
    }

    // Property accessors
    @GenericGenerator(name = "generator", strategy = "uuid.hex")
    @Id
    @GeneratedValue(generator = "generator")
    @Column(name = "USER_ID", unique = true, nullable = false, length = 32)
    public String getUserId() {
    return this.userId;
    }

    public void setUserId(String userId) {
    this.userId = userId;
    }

    @Column(name = "USER_NAM", length = 500)
    public String getUserNam() {
    return this.userNam;
    }

    public void setUserNam(String userNam) {
    this.userNam = userNam;
    }

    @Column(name = "USER_SEX", length = 1)
    public String getUserSex() {
    return this.userSex;
    }

    public void setUserSex(String userSex) {
    this.userSex = userSex;
    }

    @Column(name = "USER_PHONE", length = 11)
    public String getUserPhone() {
    return this.userPhone;
    }

    public void setUserPhone(String userPhone) {
    this.userPhone = userPhone;
    }

}


这是本人测试用的service


import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.usoft.magich.bs.ImagicServiceTest;
import com.usoft.magich.vo.MagicUser;

@Service("MagicService")
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public class MagicServiceTestImpl implements ImagicServiceTest {

@Resource
private MagicUser magicUser;

public void testMagicH() {
    //保存
    magicUser.setUserNam("用户123");
    magicUser.setUserPhone("12345");
    magicUser.setUserSex("1");
    magicUser.addObj(magicUser);

   //更新
    magicUser.setProperty("UserNam", "1234567");
    magicUser.updateObj();

    System.out.print(magicUser.getPropertyValue("UserNam"));

    boolean b1 = magicUser.init(magicUser.getClass(), "aaa");  //id 不存在初始化失败
    System.out.println(b1);

    boolean b2 = magicUser.init(magicUser.getClass(),"402881862da6ec3b012da6fb4f640004"); //id存在为 true
    System.out.println(b2);
    magicUser.delObj(); //删除 对象
}

}



只是中午吃饭时脑子那么想了一下,然后回来就尝试写了个单表的增删改查,我个人举得无论是单表还是多表最后数据库查出来的无非是个二叉表,而其中的一条记录应该对应一个java类 多条记录则是该java类的List集合,然后所有的数据库操作不再是dao.doSomething 而是entity.doSomething
我这样做了后写的代码就只有actiong,service,entity层了,不知道这样是否可行,谁能解释一下我的疑问。


问题补充
看了大家的回复深受启发,感觉自己这个想法似乎不可取就不再钻牛角尖了。
可能一直处于开发人员的角色,所以关系的核心问题无非就是 写最少的代码做最多的事
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

21条回答

为你推荐