I have just completed reading through Java Persistence with Hibernate and starting my first JPA with Hibernate project. I have written the DAO tier with the help of Hibernate tools as in chapter 16, and now considering how this will affect the rest of my application. I am considering what the book refers to as 'reference data', data that is in a table but will very, if ever, change. I am confused about how and when entities of this table should be created.
As an example. Say I had an account table and a contact preference table, with an account having a contact preference.
Code:
create table Account (
ID
FK_ContactPreference
...
);
create table ContactPreference (
ID,
Value
)
I would have a low number of entries, say three contact preferences: telephone, email, post. Value is the textual name of the preference such as 'Email'
I would map my Account to have the relationship with contact preference
Code:
public class Account implements Serializable {
@Id @GeneratedValue
long id
@ManyToOne
@JoinColumn(name="FK_ContactPreference")
ContactPreference
}
public class ContactPreference implements serializable {
@Id @GeneratedValue
long id;
String value;
}
When I construct an Account I will be setting a ContactPreference to it. However I am unsure where I would obtain it from. As I know that for instance 'Post' is id 1 can I simply contstruct it and set it? Should I load it from the database with the id I know? As I can set it to always be cached I wont suffer database hits, but calling dao would seem unusual. Can I have static instances on my ContactPreference class which I reuse, or even an enum?
My question boils down to which of these is considered the best practice?
Code:
1)
Account account = new Account();
ContactPreference contactPref = new ContactPreference();
contactPref.setId(1);
account.setContactPreference(contactPref);
accountDao.makePersistent(account);
2)
Account account = new Account();
ContactPreference contactPref = contactPrefDao.find(1);
account.setContactPreference(contactPref);
accountDao.makePersistent(account);
3)
Account account = new Account();
account.setContactPreference(ContactPreference.POST);
accountDao.makePersistent(account);
Thank you for any advice.
Martin.