1

I have 2 tables, Word and State, State contains 2 cols, ID and CurrentState, it's 3 static rows are 1-Active, 2-InActive, 3-Other Word is the table I am adding rows to. It has 4 cols, ID, Value, Description and CurrentState. It has a foreign key to State on the column currentState Here is the working code I have that creates a Word, sets it's currentState field and persists it.

Word word = new Word(); 
word.setValue("someWord");
word.setDescription("some description for this word");      
State state = new State(1,"Active");
word.setState(state);   
worddao.saveOrUpdate(word);

The thing is this just doesn't look right. What is the best practice for creating the State instance so that I can create a Word which points to a valid State row. Is Enumeration an option here? I mean I could accidently create a State with ID = 5 and violate the foreign key constraint. I want to prevent this from happening in the first place. Any ideas?

bpgergo
  • 15,669
  • 5
  • 44
  • 68
MayoMan
  • 4,757
  • 10
  • 53
  • 85
  • 1
    Yes enumeration is an option! See this http://stackoverflow.com/questions/417062/enumerations-in-hibernate – bpgergo Sep 10 '12 at 08:27
  • enums are good option - but it is more effort to add new values. If there is already conditional code for different values it is not an issue. – gkamal Sep 10 '12 at 09:30

1 Answers1

1

The safe way to do this is to look up the state object instead of creating a new one. You can mark the entity as cacheable and also mark the query to retrieve State as cacheable to avoid unnecessary queries.

Word word = new Word(); 
word.setValue("someWord");
word.setDescription("some description for this word");      
State state = stateDao.findByState("Active")
word.setState(state);   
worddao.saveOrUpdate(word);

The other option (which I generally follow) for master/reference data table is to not have an numeric ID. Just have one column which is the String representation of it and use that as the foreign key column.

The advantage with this is that when you are looking at data in the database - the word table the state will be easy to interpret. You don't have to do one more mental lookup to understand the data.

The other advantage is that caching becomes easier. We just need to cache the entity and not the query, since the lookup is always by primary key.

Later on if required you can add another column which is a display label.

gkamal
  • 20,777
  • 4
  • 60
  • 57
  • Cheers, this is what I was getting at, I was afraid that if I just queried the database each time to get the list of valid State values that this would result in unnecessary queries. Caching the table sounds like what I need, cheers – MayoMan Sep 10 '12 at 12:51