KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > User


1 package example;
2
3 import javax.persistence.*;
4
5 import javax.naming.InitialContext JavaDoc;
6 import javax.naming.Context JavaDoc;
7
8 /**
9  * Bean to handle a user.
10  *
11  * <code><pre>
12  * CREATE TABLE amber_session_user (
13  * id INTEGER
14  * name VARCHAR(255),
15  * quest VARCHAR(255),
16  * color VARCHAR(255),
17  *
18  * PRIMARY KEY(id)
19  * );
20  * </pre></code>
21  */

22 @Entity
23 @Table(name="amber_session_user")
24 public class User {
25   @Id
26   @Column(name="id")
27   @GeneratedValue
28   private int _id;
29   
30   @Basic
31   @Column(name="name")
32   private String JavaDoc _name;
33   
34   @Basic
35   @Column(name="quest")
36   private String JavaDoc _quest;
37   
38   @Basic
39   @Column(name="color")
40   private String JavaDoc _color;
41
42   public User()
43   {
44   }
45
46   public User(String JavaDoc name, String JavaDoc quest, String JavaDoc color)
47   {
48     _name = name;
49     _quest = quest;
50     _color = color;
51   }
52   
53   /**
54    * Returns the ID of the user.
55    */

56   public int getId()
57   {
58     return _id;
59   }
60   
61   public void setId(int id)
62   {
63     _id = id;
64   }
65
66   /**
67    * Returns the user's name
68    */

69   public String JavaDoc getName()
70   {
71     return _name;
72   }
73
74   /**
75    * Returns the user's quest
76    */

77   public String JavaDoc getQuest()
78   {
79     return _quest;
80   }
81
82   /**
83    * Returns the user's favorite color
84    */

85   public String JavaDoc getColor()
86   {
87     return _color;
88   }
89
90   /**
91    * When serializing, replace with the UserHandle instead.
92    */

93   private Object JavaDoc writeReplace()
94   {
95     return new UserHandle(_id);
96   }
97
98   static class UserHandle {
99     private int _id;
100
101     UserHandle(int id)
102     {
103       _id = id;
104     }
105
106     /**
107      * When deserializing return the User.
108      */

109     private Object JavaDoc readResolve()
110     {
111       try {
112     // get Amber's EntityManager from JNDI
113
Context JavaDoc ic = new InitialContext JavaDoc();
114     
115     EntityManager manager
116       = (EntityManager) ic.lookup("java:comp/env/persistence/PersistenceContext/example");
117
118     // find the user object
119
return manager.find(User.class, _id);
120       } catch (Exception JavaDoc e) {
121     throw new RuntimeException JavaDoc(e);
122       }
123     }
124   }
125 }
126
Popular Tags