是否可以不创建没有任何自定义方法的Dao类?
BuguMongo是一个轻量级的MongoDB Java开发框架,集成了DAO、Query、Lucene、GridFS等功能。
使用BuguMongo进行开发,典型的做法是,定义一个Entity类的同时,相应的定义一个Dao类。以一个模拟的新闻发布系统为例:
定义实体类News.java:
package test.mongo.news;import com.bugull.mongo.BuguEntity;import com.bugull.mongo.annotations.Entity;import com.bugull.mongo.annotations.Id;/**** @author Frank Wen(xbwen@hotmail.com)*/@Entitypublic class News implements BuguEntity{ @Id private String id; private String title; @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }?定义Dao类NewsDao.java:
package test.mongo.news;import com.bugull.mongo.BuguDao;/**** @author Frank Wen(xbwen@hotmail.com)*/public class NewsDao extends BuguDao{ public NewsDao(){ super(News.class); } public void doSomething(){ //do something here } }?然后调用该Dao的操作,例如在Struts的Action中:
package test.mongo.news;/**** @author Frank Wen(xbwen@hotmail.com)*/public class CreateNewsAction { private NewsDao newsDao; //通过Spring注入该bean public String execute(){ News news = new News(); news.setTitle("新闻标题"); newsDao.save(news); //调用BuguDao中的save方法 newsDao.doSomething(); //调用自定义的doSomething方法 return "success"; } public NewsDao getNewsDao() { return newsDao; } public void setNewsDao(NewsDao newsDao) { this.newsDao = newsDao; } }?在有些情况下,自定义的Dao类,如NewsDao.java,只需要使用BuguDao中的方法就足够了,不需要另外自定义方法(如上面的doSomething),这时候,该Dao类会像下面这样,是一个“空”的Dao类:
public class NewsDao extends BuguDao{ public NewsDao(){ super(News.class); } }?于是,就有朋友在群里问:创建这样的没有任何方法的Dao类,显得多余,能不能简单点,避免定义它呢?
package test.mongo.news;import com.bugull.mongo.BuguDao;import com.bugull.mongo.cache.DaoCache;/**** @author Frank Wen(xbwen@hotmail.com)*/public class CreateNewsAction { public String execute(){ News news = new News(); news.setTitle("新闻标题"); BuguDao dao = DaoCache.getInstance().get(News.class); dao.save(news); return "success"; } }?这样,不再需要定义NewsDao类,也不需要通过Spring注入该dao。
BuguDao dao = new BuguDao(News.class);dao.save(news);??