A Simple Entity with a Component Class
The first entity we’ll look at is a User class. This class simply represents a person, and it includes a postal address. In this design, as mentioned earlier, the user is an entity type and the address is a value type. This reflects the real world where an address is simply an attribute of a person. Listing 1 illustrates the User class.
Listing 1An Entity Type
@Entity @Table(name = "USERS") public class User { @Id @GeneratedValue @Column(name = "USER_ID") private Long id; @Embedded private Address userAddress; @Column(name = "USER_NAME") private String userName; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "NEXT_USER_ID") private User nextUser; User() {} public User(String userName) { this.userName = userName; } public Long getId() { return id; } private void setId(Long id) { this.id = id; } public Address getAddress() { return userAddress; } public void setAddress(Address address) { userAddress = address; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public User getNextUser() { return nextUser; } public void setNextUser(User nextUser) { this.nextUser = nextUser; } }
Listing 1 is very similar to the code in my previous article, “Building a Solid Foundation for JPA and Hibernate.” The main difference is the addition of a data member for a new class called Address. The Address class is our value type, and the fact that an instance of this class is contained in the User class illustrates that Address is an attribute of User. To use an object relational mapping (ORM) term, there is said to be an association (or relationship) between the User class and the Address class.
To put this in a simpler way, the Address class hangs on to the coat tails of the User class! In this way, instances of the Address class acquire a persistent identity. The remainder of the code in Listing 1 relates to methods for key management and setting and getting the member data. None of this should be a surprise, and feel free to refer to the earlier article for a quick recap.
That’s a good bit of theory, so let’s now run a simple program to see these ideas in action.