实体类的应用

 

person.java

ExpandedBlockStart.gif View Code
  1  /*
  2   * To change this template, choose Tools | Templates
  3   * and open the template in the editor.
  4    */
  5  package beans;
  6 
  7  import java.io.Serializable;
  8  import java.util.Date;
  9  import javax.persistence.*;
 10 
 11  /**
 12   *
 13   *  @author  teemu
 14    */
 15 @Entity
 16 @Table(name = "PERSON")
 17  public  class Person  implements Serializable {
 18 
 19      private  static  final  long serialVersionUID = 1L;
 20     @Id
 21     @GeneratedValue(strategy = GenerationType.AUTO)
 22      private Long id;
 23     
 24     @Column(name = "FIRST_NAME")
 25      private String firstName;
 26     
 27     @Column(name = "LAST_NAME")
 28      private String lastName;
 29     
 30     @Temporal(TemporalType.DATE)
 31      private Date dateOfBirth;
 32 
 33     @Embedded
 34      private Address address;
 35     
 36      public Person() {
 37     }
 38 
 39      public  void setId(Long id) {
 40          this.id = id;
 41     }
 42 
 43      public Long getId() {
 44          return id;
 45     }
 46 
 47      public String getFirstName() {
 48          return firstName;
 49     }
 50 
 51      public  void setFirstName(String name) {
 52         firstName = name;
 53     }
 54 
 55      public Address getAddress() {
 56          return address;
 57     }
 58 
 59      public  void setAddress(Address address) {
 60          this.address = address;
 61     }
 62 
 63      public Date getDateOfBirth() {
 64          return dateOfBirth;
 65     }
 66 
 67      public  void setDateOfBirth(Date dateOfBirth) {
 68          this.dateOfBirth = dateOfBirth;
 69     }
 70 
 71      public String getLastName() {
 72          return lastName;
 73     }
 74 
 75      public  void setLastName(String lastName) {
 76          this.lastName = lastName;
 77     }      
 78 
 79     @Override
 80      public  int hashCode() {
 81          int hash = 0;
 82         hash += (id !=  null ? id.hashCode() : 0);
 83          return hash;
 84     }
 85 
 86     @Override
 87      public  boolean equals(Object object) {
 88          //  TODO: Warning - this method won't work in the case the id fields are not set
 89           if (!(object  instanceof Person)) {
 90              return  false;
 91         }
 92         Person other = (Person) object;
 93          if (( this.id ==  null && other.id !=  null) || ( this.id !=  null && ! this.id.equals(other.id))) {
 94              return  false;
 95         }
 96          return  true;
 97     }
 98 
 99     @Override
100      public String toString() {
101          return "beans.Person[ id=" + id + ", name: "+ firstName+" "+lastName+"]";
102     }
103 }

 

personFacade.java

 

ExpandedBlockStart.gif View Code
 1  /*
 2   * To change this template, choose Tools | Templates
 3   * and open the template in the editor.
 4    */
 5  package beans;
 6 
 7  import javax.ejb.Stateless;
 8  import javax.persistence.EntityManager;
 9  import javax.persistence.PersistenceContext;
10 
11  /**
12   *
13   *  @author  teemu
14    */
15 @Stateless
16  public  class PersonFacade  extends AbstractFacade<Person> {
17     @PersistenceContext(unitName = "EntityApplication-ejbPU")
18      private EntityManager em;
19 
20     @Override
21      protected EntityManager getEntityManager() {
22          return em;
23     }
24 
25      public PersonFacade() {
26          super(Person. class);
27     }
28     
29 }

 

 

Address.java

 

ExpandedBlockStart.gif View Code
 1  /*
 2   * To change this template, choose Tools | Templates
 3   * and open the template in the editor.
 4    */
 5  package beans;
 6 
 7  import java.io.Serializable;
 8  import javax.persistence.Column;
 9  import javax.persistence.Embeddable;
10  import javax.persistence.Table;
11 
12  /**
13   *
14   *  @author  teemu
15    */
16 @Embeddable
17 @Table(name = "ADDRESS")
18  public  class Address  implements Serializable {
19 
20      private String street;
21      private String city;
22      private  int zipCode;
23      private String country;
24 
25     @Column(name = "STREET")
26      public String getStreet() {
27          return street;
28     }
29      public  void setStreet(String street) {
30          this.street = street;
31     }
32 
33     @Column(name = "CITY")
34      public String getCity() {
35          return city;
36     }
37      public  void setCity(String city) {
38          this.city = city;
39     }
40 
41     @Column(name = "STATE")
42      public  int getZipCode() {
43          return zipCode;
44     }
45      public  void setZipCode( int zipCode) {
46          this.zipCode = zipCode;
47     }
48     
49     @Column(name = "COUNTRY")
50      public String getCountry() {
51          return country;
52     }
53      public  void setCountry(String country) {
54          this.country = country;
55     }
56     
57 }

 

 

AbstractFacade.java

 

ExpandedBlockStart.gif View Code
 1  /*
 2   * To change this template, choose Tools | Templates
 3   * and open the template in the editor.
 4    */
 5 package beans;
 6 
 7 import java.util.List;
 8 import javax.persistence.EntityManager;
 9 
10  /* *
11   *
12   * @author teemu
13    */
14  public  abstract  class AbstractFacade<T> {
15      private Class<T> entityClass;
16 
17      public AbstractFacade(Class<T> entityClass) {
18          this.entityClass = entityClass;
19     }
20 
21      protected  abstract EntityManager getEntityManager();
22 
23      public  void create(T entity) {
24         getEntityManager().persist(entity);
25     }
26 
27      public  void edit(T entity) {
28         getEntityManager().merge(entity);
29     }
30 
31      public  void remove(T entity) {
32         getEntityManager().remove(getEntityManager().merge(entity));
33     }
34 
35      public T find(Object id) {
36          return getEntityManager().find(entityClass, id);
37     }
38 
39      public List<T> findAll() {
40         javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
41         cq. select(cq. from(entityClass));
42          return getEntityManager().createQuery(cq).getResultList();
43     }
44 
45      public List<T> findRange( int[] range) {
46         javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
47         cq. select(cq. from(entityClass));
48         javax.persistence.Query q = getEntityManager().createQuery(cq);
49         q.setMaxResults(range[ 1] - range[ 0]);
50         q.setFirstResult(range[ 0]);
51          return q.getResultList();
52     }
53 
54      public  int count() {
55         javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
56         javax.persistence.criteria.Root<T> rt = cq. from(entityClass);
57         cq. select(getEntityManager().getCriteriaBuilder().count(rt));
58         javax.persistence.Query q = getEntityManager().createQuery(cq);
59          return ((Long) q.getSingleResult()).intValue();
60     }
61     
62 }

 

EntityServlet.java

 

 

ExpandedBlockStart.gif View Code
  1  /*
  2   * To change this template, choose Tools | Templates
  3   * and open the template in the editor.
  4    */
  5  package servlets;
  6 
  7  import beans.Address;
  8  import beans.Person;
  9  import beans.PersonFacade;
 10  import java.io.IOException;
 11  import java.io.PrintWriter;
 12  import java.util.Calendar;
 13  import javax.ejb.EJB;
 14  import javax.servlet.ServletException;
 15  import javax.servlet.annotation.WebServlet;
 16  import javax.servlet.http.HttpServlet;
 17  import javax.servlet.http.HttpServletRequest;
 18  import javax.servlet.http.HttpServletResponse;
 19 
 20  /**
 21   *
 22   *  @author  teemu
 23    */
 24 @WebServlet(name = "EntityServlet", urlPatterns = {"/EntityServlet"})
 25  public  class EntityServlet  extends HttpServlet {
 26 
 27     @EJB
 28      private PersonFacade facade;
 29         
 30      /**
 31       * Processes requests for both HTTP
 32       * <code>GET</code> and
 33       * <code>POST</code> methods.
 34       *
 35       *  @param  request servlet request
 36       *  @param  response servlet response
 37       *  @throws  ServletException if a servlet-specific error occurs
 38       *  @throws  IOException if an I/O error occurs
 39        */
 40      protected  void processRequest(HttpServletRequest request, HttpServletResponse response)
 41              throws ServletException, IOException {
 42         response.setContentType("text/html;charset=UTF-8");
 43         PrintWriter out = response.getWriter();
 44         
 45         Person person1, person2;
 46         
 47          try {
 48               //  create John Doe
 49              person1 =  new Person();
 50             person1.setFirstName("John");
 51             person1.setLastName("Doe");
 52             Address addr =  new Address();
 53             addr.setStreet("Kidney Bean Drive 42");
 54             addr.setCity("Beanville");
 55             addr.setZipCode(12412);
 56             addr.setCountry("Beantopia");
 57             person1.setAddress(addr);
 58             Calendar c = Calendar.getInstance();
 59             c.set(1979, 3, 15);
 60             person1.setDateOfBirth(c.getTime());
 61 
 62              //  create Jane Doe
 63              person2 =  new Person();
 64             person2.setFirstName("Jane");
 65             person2.setLastName("Doe");
 66             addr =  new Address();
 67             addr.setStreet("Coffee Bean Avenue 42");
 68             addr.setCity("Beantown");
 69             addr.setZipCode(23567);
 70             addr.setCountry("Beantopia");
 71             person2.setAddress(addr);
 72             c.set(1984, 7, 23);
 73             person2.setDateOfBirth(c.getTime());
 74 
 75              //  persist John and Jane into database
 76              facade.create(person1);
 77             facade.create(person2);
 78 
 79             out.println("<html>");
 80             out.println("<head>");
 81             out.println("<title>Entity Example</title>");
 82             out.println("</head>");
 83             out.println("<body>");
 84             
 85              //  search from database
 86              Person foundPerson = facade.find(person1.getId());
 87             out.println("<br>Result of finding John with his ID: " + foundPerson.toString());
 88 
 89              //  get and print all rows from the database
 90              out.println("<br>Listing all Persons in the database: ");
 91              for (Person p : facade.findAll()) {
 92                 out.println("<br>"+p.toString());
 93             }
 94 
 95              //  update Jane's first name
 96              person2.setFirstName("Janet");
 97             facade.edit(person2);
 98             out.println("<br>Updated Jane: " + facade.find(person2.getId()).toString());
 99 
100              //  remove John            
101              facade.remove(person1);
102             out.println("<br>Removed John, printing all remaining Persons: ");
103              for (Person p : facade.findAll()) {
104                 out.println("<br>" + p.toString());
105             }
106             
107             out.println("</body>");
108             out.println("</html>");
109         }  finally {            
110             out.close();
111         }
112     }
113 
114      //  <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
115       /**
116       * Handles the HTTP
117       * <code>GET</code> method.
118       *
119       *  @param  request servlet request
120       *  @param  response servlet response
121       *  @throws  ServletException if a servlet-specific error occurs
122       *  @throws  IOException if an I/O error occurs
123        */
124     @Override
125      protected  void doGet(HttpServletRequest request, HttpServletResponse response)
126              throws ServletException, IOException {
127         processRequest(request, response);
128     }
129 
130      /**
131       * Handles the HTTP
132       * <code>POST</code> method.
133       *
134       *  @param  request servlet request
135       *  @param  response servlet response
136       *  @throws  ServletException if a servlet-specific error occurs
137       *  @throws  IOException if an I/O error occurs
138        */
139     @Override
140      protected  void doPost(HttpServletRequest request, HttpServletResponse response)
141              throws ServletException, IOException {
142         processRequest(request, response);
143     }
144 
145      /**
146       * Returns a short description of the servlet.
147       *
148       *  @return  a String containing servlet description
149        */
150     @Override
151      public String getServletInfo() {
152          return "Short description";
153     } //  </editor-fold>
154  }

 

 

index.jsp

 

ExpandedBlockStart.gif View Code
 1 <%-- 
 2     Document   : index
 3     Created on : Mar  20201211: 06: 47 AM
 4     Author     : teemu
 5 --%>
 6 
 7 <%@page contentType= " text/html " pageEncoding= " UTF-8 "%>
 8 <!DOCTYPE html>
 9 <html>
10     <head>
11         <meta http-equiv= " Content-Type " content= " text/html; charset=UTF-8 ">
12         <title>JSP Page</title>
13     </head>
14     <body>
15         <h1><a href= " EntityServlet ">Click to open the servlet</a></h1>
16     </body>
17 </html>

 

转载于:https://www.cnblogs.com/jinrize/archive/2012/04/16/2452710.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值