0

I have the following entity:

 @Entity 
 public class User {

 @Id
 @GeneratedValue
 private Integer id;
 private String name;
 private String uberField;
 }

My intention is to make uberField contain a random digit (0-9) and concat it to the char '-' and the entity id. for example:

user with id:233 will receive uberField == "6-223"

Problem is whenever i create a new entity i have to save twice because this wont work:

User newUser = new User();
newUser.setUberField(genUber(user));  // not working!!! no id yet
save(newUser);  // not working!!! no id yet

this will work:

User newUser = new User();
save(newUser);  // Save 1st
newUser.setUberField(genUber(user));
save(newUser); // save 2nd time

Can i overcome this redundant save?

Urbanleg
  • 6,252
  • 16
  • 76
  • 139
  • http://stackoverflow.com/questions/1069992/jpa-entitymanager-why-use-persist-over-merge answers my question. jpa's persist does exactly this. – Urbanleg Sep 08 '13 at 11:11

1 Answers1

0

Why do you need to save the entity ID in two fields? Can't you calculate that field while selecting data from the table instead?

One alternative solution would be to take manual control of sequence generation, and implement your own sequence number cache. That'll allow you to remove that second UPDATE. I.e if you're using Oracle:

class SequenceNumberCache {
    void init() {
        increment = jdbcTemplate.queryForInt("select increment_by from user_sequences where name = ...");
    }

    int getNextSequence() {
        if(availableValues > 0) {
            availableValues--;
            return nextValue++;
        }
        availableValues = increment - 1;
        nextValue = jdbcTemplate.queryForInt("select seq.nextval from dual");
        return nextValue++;
    }
}
Håvard
  • 767
  • 1
  • 4
  • 7