My Opera is closing 3rd of March

Đường dưới chân ta đi

Struts 2 và Hibernate kết hợp

Tạo ứng dụng kết hợp Struts 2 và Hibernate Cấu trúc của ứng dụng: I. Bước 1: Tạo ứng dụng Web trong Eclipse IDE II. Bước 2: Tạo file Web.xml
Web.xml <filter> <filter-name>struts-cleanup</filter-name> <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class> </filter> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts-cleanup</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Tạo file struts.xml trong thư mục src của project. Thêm thư viện của struts 2, gồm 5 file sau: • common-logging.jar • freemarker.jar • ognl.jar • struts2-core.jar • xwork.jar III. Bước 3: Để cấu hình Hibernate với Struts chúng ta cần thư viện của Hibernate đặt trong thư mục Web-inf/lib, gồm những file sau: antlr.jar,asm.jar,cglib.jar,commons-beanutils.jar,common-logging.jar,dom4j.jar,freemarker.jar,hibernate.jar,jta.jar, <jdbc drivers libs>, ognl.jar,struts2.jar,xwork.jar IV. Bước 4: Tạo đối tượng SessionFactory của Hibernate trong bộ lọc Struts 2,sau đó chúng ta sẽ kế thừa bộ lọc Struts 2,tạo một thư mục để plugin vào trong kiến trúc package của chúng ta. V. Bước 5: Override bộ lọc của Struts 2
HibernateUtil.java package com.net.plugin; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.Session; public class HibernateUtil { private static SessionFactory sessionFactory; public static void createSessionFactory() { sessionFactory = new Configuration().configure().buildSessionFactory(); } public static Session getSession() { return sessionFactory.openSession(); } }
Struts2dispatcher.java package com.net.plugin; import javax.servlet.*; import org.apache.struts2.dispatcher.FilterDispatcher; import org.hibernate.HibernateException; public class Struts2Dispatcher extends FilterDispatcher { @Override public void init(FilterConfig filterConfig) throws ServletException { super.init(filterConfig); try { HibernateUtil.createSessionFactory(); System.out.print(”application initializing successfully”); } catch (HibernateException e) { throw new ServletException(e);}}}
VI. Bước 6 : Cho phép bộ lọc trong file web.xml như sau: <!–<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> –> <filter-class>org.hns.plugin.Struts2Dispatcher</filter-class> VII. Bước 7: Đặt file cấu hình Hibernate trong thư mục src với tên hibernate.cfg.xm. Sử dụng MySql Tạo bảng usermast với các trường usercode(int),uname(varchar),pwd(varchar),type(varchar)
Hibernate.cfg.xml <?xml version=’1.0′ encoding=’utf-8′?> <!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD//EN” “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”> <hibernate-configuration> <session-factory> <property name=”connection.useUnicode”>true</property> <property name=”connection.characterEncoding”>UTF-8</property> <property name=”connection.driver_class”>com.mysql.jdbc.Driver</property> <property name=”connection.url”>jdbc:mysql://localhost:3306/user</property> <property name=”connection.username”>root</property> <property name=”connection.password”>root</property> <property name=”dialect”>org.hibernate.dialect.MySQLDialect</property> <property name=”current_session_context_class”>thread</property> </session-factory> </hibernate-configuration>
VIII. Bước 8: Tạo file Hiberante mapping với bảng trong cơ sở dữ liệu.Tạo lớp User.java trong package com.net.user.
User.java package com.net.user.; public class User { private int id; private String username; private String password; private String usertype; // add fields setter and getter here (required)}
Tạo file User.hbm.xml trong package com.net.user
User.hbm.xml <!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN” “http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”> <hibernate-mapping> <class name=”com.net.user.User” table=”usermast“> <id name=”id” type=”integer” column=”usercode”> <generator class=”increment”></generator> </id> <property name=”username” type=”string” column=”uname” /> <property name=”password” type=”string” column=”pwd” /> <property name=”usertype” type=”string” column=”type” /> </class> </hibernate-mapping>
Thêm phần mapping file User.hbm.xml vào hibernate.cfg.xml .Như vậy, những thành phần cài đặt cơ bản cho ứng dụng Hibernate đối với bảng User đã được hoàn thành ở đây. IX. Bước 9: Tạo một file java khác là UserHibDao để tạo và truy cập User
UserHibDao.java package com.net.user.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.net.user.User; import com.net.plugin.HibernateUtil; public class UserHibDao { private List<User> userlist; private User user; //Xóa một User public void delete(Integer id) { HibernateUtil.createSessionFactory(); Session session = HibernateUtil.getSession(); Transaction tx = null; try { tx = session.beginTransaction(); user=(User)session.get(User.class,id); session.delete(user); tx.commit(); }catch (RuntimeException e) { if(tx != null) tx.rollback(); throw e; } finally { session.close();} } //Liệt kê tất cả các User public List getAllUser() { HibernateUtil.createSessionFactory(); Session session = HibernateUtil.getSession(); try { session.beginTransaction(); userlist=session.createQuery(”from User”).list(); return userlist; } catch(Exception e) { System.out.print(”Error while fetching “+e); return null; } finally { session.close(); }} //Lấy ra một User public User getuser(Integer id) { HibernateUtil.createSessionFactory(); Session session = HibernateUtil.getSession(); try { session.beginTransaction(); //change query for get proper data Query q = session.createQuery(”from User u where u.uid=:id”); q.setInteger(”userid”,id); return (User) q.uniqueResult(); }finally { session.close(); }} //Chèn thêm 1 User public void insert(User usr) { HibernateUtil.createSessionFactory(); Session session = HibernateUtil.getSession(); Transaction tx=null; try { tx = session.beginTransaction(); session.save(usr);//saveOrUpdate() tx.commit(); } catch (RuntimeException e) { if(tx != null) tx.rollback(); throw e; } finally { session.close(); }} //Cập nhật User public void update(User usr) { HibernateUtil.createSessionFactory(); Session session = HibernateUtil.getSession(); Transaction tx = null; try { tx=session.beginTransaction(); session.update(usr); tx.commit(); }catch (RuntimeException e) { if(tx != null) tx.rollback(); throw e; } finally { session.close(); }}}
X. Bước 10: Test thử cái
public static void main(String[] args) throws Exception { UserHibDao user=new UserHibDao(); User user1 = new User(); user1.setUsername("matroi"); user1.setPassword("baby"); user1.setUsertype("demon"); user.insert(user1); System.out.println("Insert Success"); }
Kết quả chạy ầm ầm smile Vậy là test phần kết hợp giữa Hibernate và Struts 2 xong . Lúc nào rảnh post tiếp phần View và dùng cái Annotation của Hibernate 3.0 để thay thế file mapping hbm.xml

Tears in Heaven Những giọt nước mắt giữa thiên đườngLast Flight Out - Plus One

Comments

Unregistered user Thursday, May 7, 2009 7:26:20 AM

mèo writes: bạn có thể demo giữa struts và ejb ko?

Unregistered user Monday, June 8, 2009 3:47:28 PM

Good writes: Annotation của Hibernate 3.0.

Unregistered user Tuesday, March 9, 2010 4:29:32 AM

Anonymous writes: bạn nên trình bày chi tiết hơn. Trình bày như vậy rất khó hiểu cho người mới học.

Unregistered user Friday, October 22, 2010 3:57:18 AM

Anonymous writes: Hope that you can send the Hibernate library link so that we can download it. Thank you so much indeed!

Write a comment

New comments have been disabled for this post.