|
| 1 | +.categories ['Hibernate', 'Java'] |
| 2 | +.dateCreated 20080817T16:38:47 |
| 3 | +.link http://ocpsoft.org/java/hibernate-use-a-base-class-to-map-common-fields/ |
| 4 | +.mt_allow_comments 1 |
| 5 | +.mt_allow_pings 1 |
| 6 | +.mt_excerpt |
| 7 | +.mt_keywords |
| 8 | +.mt_text_more |
| 9 | +<h3>Basic Concepts:</h3> |
| 10 | +You're using Hibernate, or at least getting your feet wet at this point, so let's assume that you've started to notice a pattern. You need in all of your objects: |
| 11 | +<ul> |
| 12 | + <li>an <em>id </em>column</li> |
| 13 | + <li>a <em>version</em> column</li> |
| 14 | + <li>perhaps a <em>timestamp</em> column</li> |
| 15 | +</ul> |
| 16 | +Lets say that you are also aware of the <a href="http://www.onjava.com/pub/a/onjava/2006/09/13/dont-let-hibernate-steal-your-identity.html" target="_blank"><em>hashcode() </em>and <em>equals() </em>issues</a> that come with using objects in collections, so you want to define some basic functionality to handle that situation as well. |
| 17 | + |
| 18 | +It would be pretty nice if we could do all this in one place, keeping updates quick and painless. Well, using the EJB-3/Hibernate <em><a href="http://www.hibernate.org/hib_docs/ejb3-api/javax/persistence/MappedSuperclass.html" target="_blank">@MappedSuperclass</a> </em>annotation, we can. Mapped superclass tells Hibernate that you want all mappings defined in the base class to apply and be included in all classes which extend from it. |
| 19 | +<h3>Instructions:</h3> |
| 20 | +Let's take a look at an example base-class that will meet our above needs. |
| 21 | +<ul> |
| 22 | + <li>Copy the following code examples into your HIbernate Annotations enabled project</li> |
| 23 | +</ul> |
| 24 | +<h4>PersistentObject.java</h4> |
| 25 | +<pre lang="java">import java.io.Serializable; |
| 26 | +import java.util.Date; |
| 27 | + |
| 28 | +import javax.persistence.Column; |
| 29 | +import javax.persistence.GeneratedValue; |
| 30 | +import javax.persistence.GenerationType; |
| 31 | +import javax.persistence.Id; |
| 32 | +import javax.persistence.MappedSuperclass; |
| 33 | +import javax.persistence.Temporal; |
| 34 | +import javax.persistence.TemporalType; |
| 35 | +import javax.persistence.Version; |
| 36 | + |
| 37 | +@MappedSuperclass |
| 38 | +public abstract class PersistentObject implements Serializable |
| 39 | +{ |
| 40 | + @Id |
| 41 | + @GeneratedValue(strategy = GenerationType.AUTO) |
| 42 | + @Column(name = "id", updatable = false, nullable = false) |
| 43 | + private Long id = null; |
| 44 | + |
| 45 | + @Version |
| 46 | + @Column(name = "version") |
| 47 | + private int version = 0; |
| 48 | + |
| 49 | + @Temporal(TemporalType.TIMESTAMP) |
| 50 | + @Column(name = "last_update") |
| 51 | + private Date lastUpdate; |
| 52 | + |
| 53 | + protected void copy(final PersistentObject source) |
| 54 | + { |
| 55 | + this.id = source.id; |
| 56 | + this.version = source.version; |
| 57 | + this.lastUpdate = source.lastUpdate; |
| 58 | + } |
| 59 | + |
| 60 | + @Override |
| 61 | + public boolean equals(final Object obj) |
| 62 | + { |
| 63 | + if (this == obj) |
| 64 | + { |
| 65 | + return true; |
| 66 | + } |
| 67 | + if (obj == null) |
| 68 | + { |
| 69 | + return false; |
| 70 | + } |
| 71 | + if (!(obj instanceof PersistentObject)) |
| 72 | + { |
| 73 | + return false; |
| 74 | + } |
| 75 | + final PersistentObject other = (PersistentObject) obj; |
| 76 | + if (this.id != null && other.id != null) |
| 77 | + { |
| 78 | + if (this.id != other.id) |
| 79 | + { |
| 80 | + return false; |
| 81 | + } |
| 82 | + } |
| 83 | + return true; |
| 84 | + } |
| 85 | + |
| 86 | + protected static boolean getBooleanValue(final Boolean value) |
| 87 | + { |
| 88 | + return Boolean.valueOf(String.valueOf(value)); |
| 89 | + } |
| 90 | + |
| 91 | + public Long getId() |
| 92 | + { |
| 93 | + return this.id; |
| 94 | + } |
| 95 | + |
| 96 | + @SuppressWarnings("unused") |
| 97 | + private void setId(final Long id) |
| 98 | + { |
| 99 | + this.id = id; |
| 100 | + } |
| 101 | + |
| 102 | + public int getVersion() |
| 103 | + { |
| 104 | + return this.version; |
| 105 | + } |
| 106 | + |
| 107 | + @SuppressWarnings("unused") |
| 108 | + private void setVersion(final int version) |
| 109 | + { |
| 110 | + this.version = version; |
| 111 | + } |
| 112 | + |
| 113 | + public Date getLastUpdate() |
| 114 | + { |
| 115 | + return this.lastUpdate; |
| 116 | + } |
| 117 | + |
| 118 | + public void setLastUpdate(final Date lastUpdate) |
| 119 | + { |
| 120 | + this.lastUpdate = lastUpdate; |
| 121 | + } |
| 122 | +}</pre> |
| 123 | +<h4 style="text-align: center;">—-</h4> |
| 124 | +<h3>Extending the Base Class:</h3> |
| 125 | +Using the MockObject class from Chapter 1, now extend PersistentObject. We can remove the fields that are now mapped in PersistentObject and add new fields to fit our business needs. Notice that MockObject does not define fields or methods for <em>id</em>, <em>version</em>, <em>equals()</em>, <em>hashcode()</em>, or <em>timestamp</em>; this behavior is now contained within our mapped superclass. |
| 126 | + |
| 127 | +From now on, all you need to do to incorporate this behavior into new classes is to extend PersistentObject. |
| 128 | +<h4>MockObject.java</h4> |
| 129 | +<pre lang="java">import javax.persistence.Column; |
| 130 | +import javax.persistence.Entity; |
| 131 | +import javax.persistence.Table; |
| 132 | +import javax.persistence.Transient; |
| 133 | + |
| 134 | +@Entity |
| 135 | +@Table(name = "mock_objects") |
| 136 | +public class MockObject extends PersistentObject |
| 137 | +{ |
| 138 | + @Transient |
| 139 | + private static final long serialVersionUID = -3621010469526215357L; |
| 140 | + |
| 141 | + @Column |
| 142 | + private String textField; |
| 143 | + |
| 144 | + @Column |
| 145 | + private long numberField; |
| 146 | + |
| 147 | + public String getTextField() |
| 148 | + { |
| 149 | + return textField; |
| 150 | + } |
| 151 | + |
| 152 | + public void setTextField(String textField) |
| 153 | + { |
| 154 | + this.textField = textField; |
| 155 | + } |
| 156 | + |
| 157 | + public long getNumberField() |
| 158 | + { |
| 159 | + return numberField; |
| 160 | + } |
| 161 | + |
| 162 | + public void setNumberField(long numberField) |
| 163 | + { |
| 164 | + this.numberField = numberField; |
| 165 | + } |
| 166 | +}</pre> |
| 167 | +<h4 style="text-align: center;">—-</h4> |
| 168 | +To prove it, we'll re-run our demo application from the quick-start guide. Notice that the results are the same. I've added a little logic to show that our new columns work as well. |
| 169 | +<h4>HibernateDemo.java</h4> |
| 170 | +Our driver class does the following things: |
| 171 | +<ul> |
| 172 | + <li>Get a handle to Hibernate Session</li> |
| 173 | + <li>Create and persist two new MockObjects</li> |
| 174 | + <li>Assign values into the textField of each object</li> |
| 175 | + <li>Print out the generated IDs and set fields</li> |
| 176 | +</ul> |
| 177 | +<em>For referenced HibernateUtil,java, please see <a href="http://ocpsoft.com/java/getting-started-quickly-with-hibernate-annotations/" target="_self">Chapter 1</a>. |
| 178 | +</em> |
| 179 | +<pre lang="java">import org.hibernate.Transaction; |
| 180 | +import org.hibernate.classic.Session; |
| 181 | + |
| 182 | +public class HibernateDemo |
| 183 | +{ |
| 184 | + public static void main(String[] args) |
| 185 | + { |
| 186 | + Session session = HibernateUtil.getSessionFactory().getCurrentSession(); |
| 187 | + Transaction transaction = session.beginTransaction(); |
| 188 | + |
| 189 | + MockObject object0 = new MockObject(); |
| 190 | + object0.setTextField("I am object 0"); |
| 191 | + |
| 192 | + MockObject object1 = new MockObject(); |
| 193 | + object1.setTextField("I am object 1"); |
| 194 | + |
| 195 | + session.save(object0); |
| 196 | + session.save(object1); |
| 197 | + |
| 198 | + transaction.commit(); |
| 199 | + |
| 200 | + System.out.println("Object 0"); |
| 201 | + System.out.println(object0.getTextField()); |
| 202 | + System.out.println("Generated ID is: " + object0.getId()); |
| 203 | + System.out.println("Generated Version is: " + object0.getVersion()); |
| 204 | + |
| 205 | + System.out.println("Object 1"); |
| 206 | + System.out.println(object1.getTextField()); |
| 207 | + System.out.println("Generated ID is: " + object1.getId()); |
| 208 | + System.out.println("Generated Version is: " + object1.getVersion()); |
| 209 | + } |
| 210 | +}</pre> |
| 211 | +Which results in the following output: |
| 212 | +<pre style="padding-left: 30px;">Object 0 |
| 213 | +I am object 0 |
| 214 | +Generated ID is: 1 |
| 215 | +Generated Version is: 0 |
| 216 | + |
| 217 | +Object 1 |
| 218 | +I am object 1 |
| 219 | +Generated ID is: 2 |
| 220 | +Generated Version is: 0</pre> |
| 221 | +<h4 style="text-align: center;">—-</h4> |
| 222 | +<h4>Considering the Forces:</h4> |
| 223 | +It may be worth mentioning that using a base class for all of your objects can be a blessing and a curse. If you begin to reference objects using the more generic PersistentObject type, it is possible that you could find yourself constrained to the behavior of this one class. When this happens, consider defining PersistentObject as an <em>Interface</em> and then implement that interface with any number of <em>@MappedSuperclass</em> objects. |
| 224 | + |
| 225 | +There are benefits to referencing objects by their generic type, as well. One example, which we'll take a look at this when we dive into the <a href="http://www.hibernate.org/328.html" target="_blank"><em>Dao</em></a> pattern, makes it very easy to perform a wide array of operations on your Hibernate objects. |
| 226 | + |
| 227 | +Congratulations. You should now have a mapped superclass to contain your common functionality. |
| 228 | +<h3>References:</h3> |
| 229 | +<ol> |
| 230 | + <li><a href="http://www.hibernate.org/hib_docs/v3/reference/en/html/tutorial.html" target="_blank">Hibernate's Standard Tutorial</a></li> |
| 231 | + <li><a href="http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/" target="_blank">Hibernate Annotations Reference</a></li> |
| 232 | +</ol> |
| 233 | +This article is part of a series: <a href="http://ocpsoft.com/java/guide-to-hibernate-annotations/" target="_self">Guide to Hibernate Annotations</a> |
| 234 | +.permaLink http://ocpsoft.org/java/hibernate-use-a-base-class-to-map-common-fields/ |
| 235 | +.post_status publish |
| 236 | +.postid 8 |
| 237 | +.title Hibernate: Use a Base Class to Map Common Fields |
| 238 | +.userid 3 |
| 239 | +.wp_author_display_name Lincoln Baxter III |
| 240 | +.wp_author_id 3 |
| 241 | +.wp_password |
| 242 | +.wp_post_format standard |
| 243 | +.wp_slug hibernate-use-a-base-class-to-map-common-fields |
| 244 | +<h2>Tutorial Chapter 2 - Easier Development and Maintenance</h2> |
| 245 | +Tired of wiring in an <em>id</em>, <em>version</em>, and <em>timestamp</em> field into all of your Hibernate objects? There's an easy way to solve this pain once and for all of your classes. Avoid code-repetition: today's article focuses on using Hibernate Annotations to map common fields into one mapped superclass. |
| 246 | + |
| 247 | +If you have not done so already, and need to get a bare bones hibernate application up and running, <a href="http://ocpsoft.com/java/getting-started-quickly-with-hibernate-annotations/" target="_self">this guide</a> should get you up and running in a few minutes. |
| 248 | + |
0 commit comments