您的位置:首页 > 其它

利用开源项目Hibernate开发Blog系统

2008-03-01 14:24 501 查看
导读:
  开发工具采用MYECLIPS3.6,首先是建立项目,导入Struts+Hibernate包,然后配置SRC跟目录下的hibernate.cfg.XML.我采用的是MySQL数据库,所以配置如下:
  <hibernate-configuration>
  <session-factory>
  <!-- properties -->
  <property name="connection.username">root</property>
  <property name="connection.url">JDBC:mysql://localhost:3306/tonnyblog</property>
  <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
  <property name="connection.password"></property>
  <property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
  <!-- mapping files -->
  <mapping resource="com/tonny/blog/bean/User.hbm.xml"/>
  <mapping resource="com/tonny/blog/bean/Item.hbm.xml"/>
  <mapping resource="com/tonny/blog/bean/Review.hbm.xml"/>
  </session-factory>
  </hibernate-configuration>mapping为JavaBEAN所对应的映射。
  下面我们继续HIBERNATE程序的下步编写
  import net.sf.hibernate.HibernateException;
  import net.sf.hibernate.Session;
  import net.sf.hibernate.SessionFactory;
  import net.sf.hibernate.cfg.Configuration;
  /**
  * Description of the Class
  *
  * @author tonny
  * @created 2004年2月6日
  */
  public class HibernateUtil {
  private final static SessionFactory sessionFactory;
  static {
  try {
  sessionFactory =
  new Configuration().configure().buildSessionFactory();
  } catch (HibernateException ex) {
  throw new RuntimeException(
  "Exception building SessionFactory: "+ ex.getMessage(),ex);
  }
  }
  private HibernateUtil(){
  }
  /**
  * Description of the Field
  */
  private final static ThreadLocal session = new ThreadLocal();
  /**
  * Description of the Method
  *
  * @return Description of the Return Value
  * @exception HibernateException Description of the Exception
  */
  public static Session currentSession() throws HibernateException {
  Session s = (Session) session.get();
  if (s == null) {
  s = sessionFactory.openSession();
  session.set(s);
  }
  return s;
  }
  /**
  * Description of the Method
  *
  * @exception HibernateException Description of the Exception
  */
  public static void closeSession() throws HibernateException {
  Session s = (Session) session.get();
  session.set(null);
  if (s != null) {
  s.close();
  }
  }
  public static void init(){
  }
  }创建sessionFactory
  import net.sf.hibernate.HibernateException;
  import net.sf.hibernate.SessionFactory;
  import net.sf.hibernate.cfg.Configuration;
  import org.apache.struts.action.ActionServlet;
  import org.apache.struts.action.PlugIn;
  import org.apache.struts.config.ModuleConfig;
  import com.tonny.blog.dao.hibernate.HibernateUtil;
  public class HibernatePlugin implements org.apache.struts.action.PlugIn{
  public void init(ActionServlet servlet, ModuleConfig config){
  HibernateUtil.init();
  }
  public void destroy(){
  try{
  HibernateUtil.closeSession();
  }
  catch(HibernateException hex){
  hex.printStackTrace();
  }
  }
  }以上为HIBERNATE基本配置,对数据库操作采用DAO模式,增加配置如下:
  import com.tonny.blog.dao.hibernate.*;
  public class DAOFactory {
  private static DAOFactory instance;
  public synchronized static DAOFactory getInstance() {
  if (instance == null) {
  instance = new DAOFactory();
  }
  return instance;
  }
  private DAOFactory() {
  }
  public ItemDAO getItemDAO(){
  return new ItemDAOHibernate();
  }
  public ReviewDAO getReviewDAO(){
  return new ReviewDAOHibernate();
  }
  public UserDAO getUserDAO(){
  return new UserDAOHibernate();
  }
  }struts.xml增加配置
  <controller contentType="text/html" debug="3" locale="true" nocache="true"
  processorClass="com.tonny.blog.struts.controller.IndexRequestProcessor"/>
  <message-resources parameter="com.tonny.resource"/>
  <plug-in className="com.tonny.blog.struts.plugin.HibernatePlugin"/>
  <plug-in className="org.apache.struts.tiles.TilesPlugin">
  <set-property property="moduleAware" value="true"/>
  <set-property property="definitions-debug" value="0"/>
  <set-property property="definitions-parser-details" value="0"/>
  <set-property property="definitions-parser-validate" value="false"/>
  <set-property property="definitions-config" value="/Web-INF/title-def.xml"/>
  </plug-in>下面我们定义服务层:
  public class ServiceFactory{
  private static ServiceFactory instance;
  public synchronized static ServiceFactory getInstance() {
  if (instance == null) {
  instance = new ServiceFactory();
  }
  return instance;
  }
  private ServiceFactory(){
  }
  public IService getService(){
  return new ServiceImp();
  }
  }import com.tonny.blog.struts.form.*;
  import com.tonny.blog.view.*;
  import com.tonny.blog.bean.*;
  import java.util.*;
  import javax.servlet.http.*;
  public interface IService{
  public UserContainer login(UserForm userForm);
  public boolean logout(UserContainer userContainer);
  public boolean addBlog(BlogForm blogForm,String filePath);
  public boolean removeBlog(Long id);
  public boolean addReview(Long topicId,ReviewForm reviewForm);
  public boolean updateBlog(Long id,String conten,String topic);
  public boolean removeReview(Long id);
  public List getItems();
  public ItemView getItem(Long id);
  public ItemView getEditItem(Long id);
  public List search(SearchForm searchForm);
  /**
  * @param id
  * @param userForm
  */
  public boolean addUser(UserForm userForm);
  }import com.tonny.blog.struts.form.*;
  import com.tonny.blog.view.*;
  import com.tonny.blog.dao.*;
  import com.tonny.blog.bean.*;
  import java.util.*;
  import javax.servlet.http.*;
  import com.tonny.blog.struts.util.FileUpload;
  public class ServiceImp implements IService{
  public UserContainer login(UserForm userForm){
  UserDAO userDAO=DAOFactory.getInstance().getUserDAO();
  User user=userDAO.loadUser(userForm.getName());
  if(user==null)return new UserContainer("",false);
  if(!user.getPassword().equals(userForm.getPassword()))return new UserContainer("",false);
  return new UserContainer(userForm.getName(),true);
  }
  public boolean logout(UserContainer userContainer){
  userContainer.setLogin(false);
  userContainer.setName("");
  return true;
  }
  public boolean addBlog(BlogForm blogForm,String path) {
  ItemDAO itemDAO=DAOFactory.getInstance().getItemDAO();
  Item item=new Item(blogForm.getTopic(),blogForm.getContent(),
  FileUpload.upload(blogForm.getFile(),path),new Date());
  itemDAO.addItem(item);
  return true;
  }
  public boolean removeBlog(Long id) {
  ReviewDAO reviewDAO=DAOFactory.getInstance().getReviewDAO();
  ItemDAO itemDAO=DAOFactory.getInstance().getItemDAO();
  itemDAO.removeItem(id);
  return reviewDAO.removeReviews(id);
  }
  public boolean addReview(Long topicId,ReviewForm reviewForm){
  ReviewDAO reviewDAO=DAOFactory.getInstance().getReviewDAO();
  Review review=new Review(reviewForm.getName(),reviewForm.getContent(),
  topicId,new Date());
  return reviewDAO.addReview(review);
  }
  public boolean updateBlog(Long id,String content,String topic){
  ItemDAO itemDAO=DAOFactory.getInstance().getItemDAO();
  Item item=new Item();
  item.setId(id);
  item.setContent(content);
  item.setTopic(topic);
  return itemDAO.updatItem(item);
  }
  public boolean addUser(UserForm userForm){
  UserDAO userDAO=(UserDAO) DAOFactory.getInstance().getUserDAO();
  User user=new User(userForm.getName(),userForm.getPassword());
  return userDAO.addUser(user);
  }
  public boolean removeReview(Long id){
  ReviewDAO reviewDAO=DAOFactory.getInstance().getReviewDAO();
  return reviewDAO.removeReview(id);
  }
  public List getItems(){
  ItemDAO itemDAO=DAOFactory.getInstance().getItemDAO();
  List items=itemDAO.loadItems();
  List itemViews=new ArrayList();
  for(Iterator it=items.iterator();it.hasNext();){
  Item item=(Item)it.next();
  ItemView itemView=new ItemView();
  itemView.setContent(item.getContent());
  itemView.setDate(item.getDate());
  itemView.setFile(item.getFile());
  itemView.setId(item.getId());
  itemView.setTopic(item.getTopic());
  itemViews.add(itemView);
  }
  return itemViews;
  }
  public ItemView getEditItem(Long id){
  ItemDAO itemDAO=DAOFactory.getInstance().getItemDAO();
  Item item=itemDAO.loadItem(id);
  ItemView itemView=new ItemView();
  itemView.setContent(item.getContent());
  itemView.setDate(item.getDate());
  itemView.setFile(item.getFile());
  itemView.setId(item.getId());
  itemView.setTopic(item.getTopic());
  return itemView;
  }
  public List search(SearchForm searchForm) {
  ItemDAO itemDAO=DAOFactory.getInstance().getItemDAO();
  List items=itemDAO.loadItems(searchForm.getKeyword());
  List itemViews=new ArrayList();
  for(Iterator it=items.iterator();it.hasNext();){
  Item item=(Item)it.next();
  ItemView itemView=new ItemView();
  itemView.setContent(item.getContent());
  itemView.setDate(item.getDate());
  itemView.setFile(item.getFile());
  itemView.setId(item.getId());
  itemView.setTopic(item.getTopic());
  itemViews.add(itemView);
  }
  return itemViews;
  }
  }下面是ACTION如何调用以上个服务:
  import java.io.*;
  import javax.servlet.RequestDispatcher;
  import javax.servlet.ServletException;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpSession;
  import javax.servlet.http.HttpServletResponse;
  import org.apache.struts.action.Action;
  import org.apache.struts.action.ActionError;
  import org.apache.struts.action.ActionErrors;
  import org.apache.struts.action.ActionForm;
  import org.apache.struts.action.ActionForward;
  import org.apache.struts.action.ActionMapping;
  import org.apache.struts.action.ActionServlet;
  import org.apache.struts.util.MessageResources;
  import com.tonny.blog.struts.form.*;
  public class AddBlog extends BlogBaseAction{
  //------------------------------------------------------------ Local Forwards
  static final private String FORWARD_success = "success";
  static final private String FORWARD_failure = "failure";
  //------------------------------------------------------------ Action Methods
  public ActionForward execute(ActionMapping mapping, ActionForm form,
  HttpServletRequest request, HttpServletResponse response)
  throws Exception {
  if(!isLogin(request))return mapping.findForward(FORWARD_failure);
  service.addBlog((BlogForm)form,((BlogForm)form).getFile().getFileName());
  return mapping.findForward(FORWARD_success);
  }
  }下一步为DAO层来操作数据库:
  import com.tonny.blog.bean.*;
  import java.util.List;
  public interface ItemDAO {
  public boolean addItem(Item item);
  public boolean removeItem(Long id);
  public List loadItems();
  public List loadItems(String topic);
  public Item loadItem(Long id);
  public boolean updatItem(Item item);
  }DAOFACTORY调用实力化方法:
  import com.tonny.blog.dao.*;
  import net.sf.hibernate.cfg.Configuration;
  import net.sf.hibernate.*;
  import java.util.*;
  import com.tonny.blog.bean.*;
  public class ItemDAOHibernate extends DAOHibernate implements ItemDAO {
  public ItemDAOHibernate(){
  }
  public boolean addItem(Item item){
  try{
  beginTransaction();
  session.save(item);
  commit();
  return true;
  }
  catch(HibernateException e){
  rollback();
  return false;
  }
  }
  public boolean updatItem(Item item){
  try{
  beginTransaction();
  Item it=item;
  it=(Item)session.load(Item.class,(item.getId()));
  it.setTopic(item.getTopic());
  System.out.println("item.getTopic()"+item.getTopic());
  it.setContent(item.getContent());
  System.out.println("item.getContent()"+item.getContent());
  session.flush();
  commit();
  return true;
  }
  catch(HibernateException e){
  System.err.println("========>hibernate exception"+e);
  rollback();
  return false;
  }
  }
  public boolean removeItem(Long id){
  try{
  beginTransaction();
  session.delete("from com.tonny.blog.bean.Item as item where item.id="+id);
  commit();
  return true;
  }
  catch(HibernateException e){
  rollback();
  return false;
  }
  }
  public List loadItems(){
  List list=null;
  try{
  beginTransaction();
  list=session.find("from com.tonny.blog.bean.Item as item");
  commit();
  }
  catch(HibernateException e){
  System.out.println("load Blog failed");
  rollback();
  }
  return list;
  }
  public List loadItems(String topic){
  List list=null;
  try{
  beginTransaction();
  Query query=session.createQuery("from com.tonny.blog.bean.Item as item where item.topic like '%"+topic+"%'");
  list=query.list();
  commit();
  return list;
  }
  catch(HibernateException e){
  System.out.println("load blog failed");
  rollback();
  }
  return list;
  }
  public Item loadItem(Long id){
  Item item=null;
  try{
  beginTransaction();
  Query query=session.createQuery("from com.tonny.blog.bean.Item as item where item.id=:id");
  query.setLong("id",id.longValue());
  Iterator it=query.iterate();
  if(it.hasNext()) return item=(Item)it.next();
  commit();
  }
  catch(HibernateException e){
  System.out.println("load blog failed");
  rollback();
  }
  return item;
  }
  }这里实现了对数据库查询,修改,删除操作,没有MANY-TO-MANY操作。

本文转自
http://hi.baidu.com/xiaoxiaolq/blog/item/28d609d86e8c9c3132fa1cf7.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息