java - adding static property data when creating entities -
suppose have 2 entity types: user , country.
country entities never created , aren't mutable. they're keyed iso alpha3 country codes, e.g. "usa". reside in table country pk column id.
users have many-to-one mapping country w/ cascade = none. users reside in user table fk column country_id references country(id).
when creating new user might like:
user user = new user(); user.setcountry(em.find(country.class, "usa")); em.persist(user);
i gather that's wasteful, though, since requires query against country first. noticed can this:
country usa = new country(); usa.setid("usa"); user user = new user(); user.setcountry(usa); em.persist(user);
since cascade = "none" shouldn't need query country table; should insert "usa" directly user country_id. correct?
now suppose there's code ever creates users country_id = "usa". in case, occurred me store static instance of country id = "usa" , use every new user? example:
public class usauserfactory implements factory<user> { private static final country usa = new country(); static { usa.setid("usa"); } public user newinstance() { user user = new user(); user.setcountry(usa); return user; } } public someotherclass { public void persistuser(entitymanager em, factory<user> uf, ...) { user user = uf.newinstance(); // set other properties em.persist(user); } }
assume persistuser() called concurrently multiple threads , within multiple persistence contexts.
my questions:
will persisting user entities mutate singleton "usa" country instance in way?
is inadvisable other reasons entirely?
the 2 classes above illustrate question; i'm not doing quite silly.
i more inclined try using cache read-only data reduce actual database calls. see here setting cache might help.
Comments
Post a Comment