做一個程式碼備份,以後常用到的。
hibernate工具類備份
package com.dly.service; /* * hibernate獲取session 的工具類 */ import java.io.Serializable; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.Session; public final class HibernateUtil { private static SessionFactory sessionFactory; public static SessionFactory getSessionFactory() { return sessionFactory; } private HibernateUtil(){ } static{ Configuration cfg=new Configuration(); cfg.configure();//配置檔名 sessionFactory=cfg.buildSessionFactory(); } public static Session getSession(){ return sessionFactory.openSession(); } /** * 新增資訊 * @param entity */ public static void add(Object entity){ Session s=null; Transaction tx=null; try{ s=HibernateUtil.getSession(); tx=s.beginTransaction(); s.save(entity); tx.commit(); }finally{ if(s!=null){ s.close(); } } } /** * 更新資訊 * @param entity */ public static void update(Object entity){ Session s=null; Transaction tx=null; try{ s=HibernateUtil.getSession(); tx=s.beginTransaction(); s.update(entity); tx.commit(); }finally{ if(s!=null){ s.close(); } } } /** * 刪除資訊 * @param entity */ public static void delete(Object entity){ Session s=null; Transaction tx=null; try{ s=HibernateUtil.getSession(); tx=s.beginTransaction(); s.delete(entity); tx.commit(); }finally{ if(s!=null){ s.close(); } } } /** * 根據id查詢 * @param clazz * @param id * @return */ public static Object get(Class clazz,Serializable id){ Session s=null; try{ s=HibernateUtil.getSession(); Object obj=s.get(clazz, id); return obj; }finally{ if(s!=null){ s.close(); } } } }
運算元據庫舉例:
package com.dly.service; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import com.dly.entity.Users; public class UserDao { public static String queryByname(String name){ Session s=null; String result=null; //System.out.println("呼叫了"); try{ s=HibernateUtil.getSession(); String hql="from Users as user where user.username=:username";//裡面User是類名,不是表名,為類名起別名user,查詢的是物件 Query query=s.createQuery(hql); query.setString("username", name); Users u=(Users) query.uniqueResult();//確定只有一個資料,限制使用者名稱唯一時使用 // System.out.println(u.getUsername()); if(u!=null){ result=u.getUsername(); System.out.println(result); } return result; }finally{ if(s!=null){ s.close(); } } } public static Users queryByusername(String username,String pwd){ Users user=null; Session s=null; try{ s=HibernateUtil.getSession(); String hql="from Users as users where users.username=:username";//裡面User是類名,不是表名,為類名起別名user,查詢的是物件 Query query=s.createQuery(hql); query.setString("username", username); List<Users>list =query.list(); for(Users users:list){ String u=users.getUsername(); String p=users.getPassword(); if(u.equals(username)&&p.equals(pwd)){ user=users; } } return user; }finally{ if(s!=null){ s.close(); } } } }
servlet常用程式碼舉例:
package com.dly.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import com.dly.entity.Shop; import com.dly.service.BuyCarDao; import com.dly.service.HibernateUtil; @WebServlet("/BuyCarList") public class BuyCarList extends HttpServlet { private static final long serialVersionUID = 1L; // Class clazz=BuyCar.class; Class<Shop> clazz=Shop.class; List<Shop> shop=new ArrayList<Shop>(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); int userid=Integer.parseInt(request.getParameter("userid")); List<Integer> list=new ArrayList<Integer>(); list=BuyCarDao.querayByuserid(userid); Iterator<Integer> it=list.iterator(); List<Shop>shop=new ArrayList<Shop>(); while(it.hasNext()){ int shopid=(Integer) it.next(); shop.add((Shop) HibernateUtil.get(clazz, shopid)); } JSONArray shoplist=new JSONArray(shop); response.getWriter().println(shoplist.toString()); } }
package com.dly.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dly.entity.BuyCar; import com.dly.service.BuyCarDao; import com.dly.service.HibernateUtil; @WebServlet("/AddBuyCar") public class AddBuyCar extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); BuyCar buycar; int shopid = Integer.parseInt(request.getParameter("shopid")); int userid=Integer.parseInt(request.getParameter("userid")); BuyCar result =BuyCarDao.queryByshopid(shopid); if(result==null){ buycar=new BuyCar(); buycar.setShopid(shopid); buycar.setUserid(userid); HibernateUtil.add(buycar); response.getWriter().print("新增成功"); response.getWriter().flush(); }else{ response.getWriter().print("該商品已在購物車中"); response.getWriter().flush(); } } }
hibernate配置檔案編寫
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 對映檔案 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/trade?useUnicode=true&characterEncoding=UTF-8</property> <property name="connection.username">root</property> <property name="connection.password"></property> <property name="dialect"> org.hibernate.dialect.MySQLDialect</property> <mapping resource="com/dly/entity/Users.hbm.xml"/> </session-factory> </hibernate-configuration>
Users.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.dly.entity"> <class name="Users" table="users" > <!-- id值 --> <id name="userid" type="int" length="11"> <generator class="native"/> </id> <property name="username" type="string" length="32" column="username"></property> <property name="password" type="string" length="32" column="password"></property> <property name="school" type="string" length="64" column="school"></property> <property name="userphone" type="string" length="32" column="userphone"></property> </class> </hibernate-mapping>
此程式碼正在完善中。。。。。。