Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 25 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
25
Dung lượng
1,26 MB
Nội dung
Enterprise Application Development in Java EE Lab09 - 10 Persistence of Entities Advanced Persistence Concepts Mục tiêu - Tạo Entity Class Persistence Unit ứng dụng Enterprise - Tạo liên kết thực thể - Tạo Web Client để test Phần I Bài tập step by step Bài 6.1 Tạo Entity Class từ bảng Database tạo Persistence Unit từ JNDI Step 1: Tạo Database CRMDB Tạo bảng Customer có trường CustomerId: Int, Primary Key, Identity(1,1) CustomerName: Nvarchar(50) IT Research Department @BKAP 2015 Page / 25 Enterprise Application Development in Java EE Step 2: Tạo JDBC Connection Pools có tên CRMPool kết nối với CRMDB Step 3: Tạo JDBC Resources có tên jdbc/CRMDS với Pool Name CRMDB Step 4: Tạo ứng dụng Enterprise CRMApplication IT Research Department @BKAP 2015 Page / 25 Enterprise Application Development in Java EE Ứng dụng sau hoàn thành Step 5: Tạo Entity Class Customer Persistence Unit CRMApplication-ejb New Other Persistence Entity Class IT Research Department @BKAP 2015 Page / 25 Enterprise Application Development in Java EE IT Research Department @BKAP 2015 Page / 25 Enterprise Application Development in Java EE Ứng dụng sau hoàn thành Customer.java package entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; IT Research Department @BKAP 2015 Page / 25 Enterprise Application Development in Java EE /** * * @author Quang */ //Map Customer Entity voi table Customer @Entity @Table(name = "Customer") public class Customer implements Serializable { private static final long serialVersionUID = 1L; //Map id voi column CustomerID @Id @Column(name = "CustomerId") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; //Map customerName voi column CustomerName @Column(name = "CustomerName") private String customerName; //Getter and Setter public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Customer)) { return false; } Customer other = (Customer) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } IT Research Department @BKAP 2015 Page / 25 Enterprise Application Development in Java EE //Override phuong thuc toString @Override public String toString() { return "entity.Customer[ id=" + id + " , name=" + customerName + " ]"; } } persistence.xml jdbc/CRMDS false Step 6: Tạo Stateless Session Bean với tên CustomerBean thực tạo Customer CRMApplication-ejb New Other Enterprise JavaBeans Session Bean IT Research Department @BKAP 2015 Page / 25 Enterprise Application Development in Java EE Khai báo phương thức tạo Customer CustomerBeanLocal.java package beanpack; IT Research Department @BKAP 2015 Page / 25 Enterprise Application Development in Java EE import entity.Customer; import javax.ejb.Local; /** * * @author Quang */ @Local public interface CustomerBeanLocal { public void createCustomer(Customer customer); } Thực nghiệp vụ tạo Customer CustomerBean.java package beanpack; import entity.Customer; import javax.ejb.Stateless; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author Quang */ @Stateless @TransactionManagement(TransactionManagementType.CONTAINER) public class CustomerBean implements CustomerBeanLocal { //Persistence @PersistenceContext(unitName = "CRMApplication-ejbPU") EntityManager em; @Override public void createCustomer(Customer customer) { em.persist(customer); } } Step 7: Tạo form nhập thông tin Customer: CustomerForm.jsp CRMApplication-war Web Pages New Other Web JSP CustomerForm.jsp IT Research Department @BKAP 2015 Page / 25 Enterprise Application Development in Java EE Create Customer Create Customer Customer Name: Step 8: Tạo Servlet CustomerServlet CRMApplication-war New Other Web Servlet IT Research Department @BKAP 2015 Page 10 / 25 Enterprise Application Development in Java EE CustomerServlet.java IT Research Department @BKAP 2015 Page 11 / 25 Enterprise Application Development in Java EE package servlet; import beanpack.CustomerBeanLocal; import entity.Customer; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Quang */ public class CustomerServlet extends HttpServlet { @EJB private CustomerBeanLocal customerBean; /** * Processes requests for both HTTP GET and POST * methods * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String customerName = request.getParameter("customerName"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here You may use following sample code */ out.println(""); out.println(""); out.println(""); out.println("Servlet CustomerServlet"); out.println(""); out.println(""); //Khoi tao Customer Entity va set thuoc tinh customerName cho no Customer customer = new Customer(); customer.setCustomerName(customerName); //thuc hien them customer try { customerBean.createCustomer(customer); out.println("Create Customer Success!"); } catch (Exception e) { out.println("Error processing for create Customer!"); } out.println(""); out.println(""); } } IT Research Department @BKAP 2015 Page 12 / 25 Enterprise Application Development in Java EE // /** * Handles the HTTP GET method * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP POST method * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// } Step 9: Set trang CustomerForm.jsp trang home web.xml CustomerServlet servlet.CustomerServlet IT Research Department @BKAP 2015 Page 13 / 25 Enterprise Application Development in Java EE CustomerServlet /CustomerServlet 30 CustomerForm.jsp Step 10: Build and Run Application Bài 6.2 Tạo liên kết khóa ngoại Customer Entity Address Entity Tạo Web Client để test liên kết Step 1: Tạo bảng Address database CRMDB (Bài 6.1) IT Research Department @BKAP 2015 Page 14 / 25 Enterprise Application Development in Java EE Step 2: Tạo Address Entity package entity module CRMApplication-ejb (bài 6.1) Tạo mối liên kết Address Entity Customer Entity CRMApplication-ejb Source Packages entity RC New Other Persistence Entity Class IT Research Department @BKAP 2015 Page 15 / 25 Enterprise Application Development in Java EE IT Research Department @BKAP 2015 Page 16 / 25 Enterprise Application Development in Java EE Address.java package entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * * @author Quang */ @Entity @Table(name = "Address") public class Address implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "AddressId") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } //Mapped cac cot cua bang voi cac field @Column(name = "AddressType") private String addressType; @Column(name = "AddressLine") private String addressLine; //Lien ket Address voi Customer @ManyToOne @JoinColumn(name = "CustomerId") private Customer customer; //Getter and Setter public String getAddressType() { return addressType; } public void setAddressType(String addressType) { this.addressType = addressType; IT Research Department @BKAP 2015 Page 17 / 25 Enterprise Application Development in Java EE } public String getAddressLine() { return addressLine; } public void setAddressLine(String addressLine) { this.addressLine = addressLine; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Address)) { return false; } Address other = (Address) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "entity.Address[ id=" + id + " ]"; } } Sửa Customer Entity để map One to Many với Address package entity; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; IT Research Department @BKAP 2015 Page 18 / 25 Enterprise Application Development in Java EE import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; /** * * @author Quang */ //Map Customer Entity voi table Customer @Entity @Table(name = "Customer") public class Customer implements Serializable { private static final long serialVersionUID = 1L; //Map id voi column CustomerID @Id @Column(name = "CustomerId") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; //Map customerName voi column CustomerName @Column(name = "CustomerName") private String customerName; //Map One to Many voi Address @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "Customer") private List listAddress; //Constuctor public Customer() { this.listAddress = new ArrayList(); } //Getter and Setter public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public List getListAddress() { return listAddress; } public void setListAddress(List listAddress) { IT Research Department @BKAP 2015 Page 19 / 25 Enterprise Application Development in Java EE this.listAddress = listAddress; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Customer)) { return false; } Customer other = (Customer) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } //Override phuong thuc toString @Override public String toString() { return "entity.Customer[ id=" + id + " , name=" + customerName + " ]"; } } Step 3: Chỉnh sửa nghiệp vụ tạo Customer Customer Bean CustomerBeanLocal.java package beanpack; import entity.Address; import entity.Customer; import java.util.List; import javax.ejb.Local; /** * * @author Quang */ @Local public interface CustomerBeanLocal { public void createCustomer(Customer customer, List listAddress); } CustomerBean.java package beanpack; IT Research Department @BKAP 2015 Page 20 / 25 Enterprise Application Development in Java EE import entity.Address; import entity.Customer; import java.util.List; import javax.ejb.Stateless; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author Quang */ @Stateless @TransactionManagement(TransactionManagementType.CONTAINER) public class CustomerBean implements CustomerBeanLocal { //Persistence @PersistenceContext(unitName = "CRMApplication-ejbPU") EntityManager em; @Override public void createCustomer(Customer customer, List listAddress) { customer.setListAddress(listAddress); for (Address addr : listAddress) { addr.setCustomer(customer); } em.persist(customer); } } Step 4: Tạo Web Client để test mối liên kết Entity CRMApplication-war CustomerForm.jsp Create Customer Create Customer Customer Name: Present Address: Permanent Address: CRMApplication-war CustomerServlet.java IT Research Department @BKAP 2015 Page 21 / 25 Enterprise Application Development in Java EE package servlet; import beanpack.CustomerBeanLocal; import entity.Address; import entity.Customer; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Quang */ public class CustomerServlet extends HttpServlet { @EJB private CustomerBeanLocal customerBean; /** * Processes requests for both HTTP GET and POST * methods * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String customerName = request.getParameter("customerName"); String presAddress = request.getParameter("presAddress"); String permAddress = request.getParameter("permAddress"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here You may use following sample code */ out.println(""); out.println(""); out.println(""); out.println("Servlet CustomerServlet"); out.println(""); out.println(""); //Khoi tao Customer Entity va set thuoc tinh customerName cho no Customer customer = new Customer(); customer.setCustomerName(customerName); List listAddress = new ArrayList(); //Add Present Address if (presAddress != null && !presAddress.isEmpty()) { Address addr = new Address(); addr.setAddressType("Present"); addr.setAddressLine(presAddress); listAddress.add(addr); IT Research Department @BKAP 2015 Page 22 / 25 Enterprise Application Development in Java EE } //Add Permanent Address if (permAddress != null && !permAddress.isEmpty()) { Address addr = new Address(); addr.setAddressType("Permanent"); addr.setAddressLine(permAddress); listAddress.add(addr); } //thuc hien them customer try { customerBean.createCustomer(customer, listAddress); out.println("Create Customer Success!"); } catch (Exception e) { out.println("Error processing for create Customer!"); } out.println(""); out.println(""); } } // /** * Handles the HTTP GET method * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP POST method * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet * * @return a String containing servlet description */ IT Research Department @BKAP 2015 Page 23 / 25 Enterprise Application Development in Java EE @Override public String getServletInfo() { return "Short description"; }// } Step 5: Build and Run Application IT Research Department @BKAP 2015 Page 24 / 25 Enterprise Application Development in Java EE IT Research Department @BKAP 2015 Page 25 / 25 ... entity.Customer; import java. io.IOException; import java. io.PrintWriter; import java. util.ArrayList; import java. util.List; import javax .ejb. EJB; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet;... entity.Customer; import java. io.IOException; import java. io.PrintWriter; import javax .ejb. EJB; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest;... java. util.List; import javax .ejb. Stateless; import javax .ejb. TransactionManagement; import javax .ejb. TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext;