java web从零单排地二十期《Hibernate》基本流程
1.新建包com.hibernate.util,添加类HibernateUtil.java
package com.hibernate.util;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil {private static SessionFactory sessionFactory;static {try{ sessionFactory = new Configuration().configure().buildSessionFactory();}catch(Exception e){e.printStackTrace();}}public static Session currentSession(){Session session = sessionFactory.openSession();return session;}public static void closeSession(Session session){if(session!=null){session.close();}}}
这段代码主要完成session的创建与删除。我们首先分析代码块:
private static SessionFactory sessionFactory;
声明一个SessionFactory,什么是SessionFactory?
package com.hibernate.persistence;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import com.hibernate.model.User;import com.hibernate.util.HibernateUtil;public class UserDB{public static void save(User user){ Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); try{session.save(user);tx.commit();}catch (Exception ex){System.out.println("增加用户出现异常");if(null!=tx)tx.rollback();// TODO: handle exception} finally { HibernateUtil.closeSession(session); }}//查询出所有用户@SuppressWarnings("unchecked")public static List<User> listall(){List<User> list = null; Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); try{Query query = session.createQuery("from User");//HQL 语句,针对的是类,不是具体的表 list =(List<User>) query.list(); tx.commit();}catch (Exception ex){System.out.println("增加用户出现异常");if(null!=tx)tx.rollback();// TODO: handle exception} finally { HibernateUtil.closeSession(session); } return list;}public static User getUserById(Integer Id){User user =null; Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); try{//Query query = session.createQuery("from User where id=username");//HQL 语句,针对的是类,不是具体的表 //Object get(Class clazz, Serializable id) user =(User)session.get(User.class, Id); tx.commit();}catch (Exception ex){System.out.println("getUserById出现异常");if(null!=tx)tx.rollback();// TODO: handle exception} finally { HibernateUtil.closeSession(session); } return user;}public static void removeById(int id){Session session = HibernateUtil.currentSession();Transaction ts = session.beginTransaction();User user = null;try{user = (User)session.get(User.class, id);session.delete(user);ts.commit();}catch (Exception e){// TODO: handle exceptionif(null!=ts){ts.rollback();}}}}对于接触过数据的同学应该不难理解,里面出现了一个Transaction,他是一个事务,执行其commit方法进行提交。
3.新建com.test.action包,添加类UserAction:
package com.test.action;import java.util.List;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import org.apache.struts2.ServletActionContext;import com.hibernate.model.User;import com.hibernate.persistence.UserDB;import com.opensymphony.xwork2.ActionSupport;import com.sun.xml.internal.ws.resources.HttpserverMessages;public class UserAction extends ActionSupport{ public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}private String username; private String password;//完成用户增加的操作public String save() throws Exception{User user = new User();user.setUsername(username);user.setPassword(password);UserDB.save(user);//保存到数据库了List<User> list = UserDB.listall();HttpServletRequest request = ServletActionContext.getRequest();request.setAttribute("list", list);return SUCCESS;}public String getUser() throws Exception{User user = UserDB.getUserById(username);HttpServletRequest request = ServletActionContext.getRequest();request.setAttribute("user", user);return SUCCESS;}public String deleteUser() throws Exception{UserDB.removeById(username);List<User> list =UserDB.listall();HttpServletRequest request = ServletActionContext.getRequest();request.setAttribute("list", list);return SUCCESS;}}
4.struts.xml文件:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtd/struts-2.0.dtd"><struts><package name="hibernate" extends="struts-default"> <action name="save" class="com.test.action.UserAction" method="save"> <result name="success" >/listAll.jsp</result> </action> <action name="getUser" class="com.test.action.UserAction" method="getUser"> <result name="success">/getPerson.jsp</result> </action> <action name="deleteUser" class="com.test.action.UserAction" method="deleteUser"> <result name="success">/listAll.jsp</result> </action></package></struts>
listall.jsp getPersion.jsp还没有添加,会在下一期一起讲解。
这一期的内容较多,到此先让同学们消化消化,下一期会结合jsp页面进行添加和删除。