0

Suppose I have two entity types: User and Country.

Country entities are never created and aren't mutable. They're keyed by ISO alpha3 country codes, e.g. "USA". They reside in the table COUNTRY with PK column ID.

Users have a many-to-one mapping to Country w/ cascade = none. Users reside in the USER table with a FK column COUNTRY_ID that references COUNTRY(ID).

When creating a new User I might do something like:

User user = new User();
user.setCountry(em.find(Country.class, "USA"));
em.persist(user);

I gather that's wasteful, though, since it requires a query against COUNTRY first. So I noticed I can also do this:

Country usa = new Country();
usa.setId("USA");
User user = new User();
user.setCountry(usa);
em.persist(user);

Since cascade = "none" this shouldn't need to query the COUNTRY table; it should just insert "USA" directly into USER as COUNTRY_ID. Is that correct?

Now suppose there's some code that only ever creates Users with COUNTRY_ID = "USA". In that case, it occurred to me to store a static instance of Country with ID = "USA" and use it for every new user? For 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 some other properties
        em.persist(user);
    }
}

Assume persistUser() is called concurrently from multiple threads and from within multiple persistence contexts.

My questions:

  1. Will persisting User entities mutate my singleton "USA" Country instance in any way?

  2. Is this inadvisable for some other reasons entirely?

The two classes above are just to illustrate the question; I'm not actually doing anything quite that silly.

1 Answer 1

1

I would be more inclined to try using a cache for the read-only data to reduce the actual database calls. See here for help setting up a cache that might help.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.