views:

38

answers:

2

Supposing I have a Person class that is persisted/loaded via hibernate:

class 
{
int PersonId;
String Name;
}

PersonId is an "autonumber" that is generated by hibernate when saving the Person.
Now lets say I made a bunch of Person's in a test database that I now want to copy over to the Production database.
But, in Production database, there is already a PersonId of 1 called "John".
And in Test database, PersonId 1 is "William".

How would I import "William" as PersonId=2 into the Production database?

Note that there will be other tables where PersonId is used in the Test database like Address table etc. So all of that also needs to be exported/imported, while maintaing the integrity of PersonId..

EDIT: I suppose one possiblilty is that the Test database should be configured to use autonumber starting at say 90,000 while we know that the Production database has values of PersonId less than 10,000. So we can "split" it that way. But what if the user forgot to set that and is now stuck with autonumbers starting from 1? The user shouldn't have to redo all the effort just to change the id's that my s/w should ideally be doing..

A: 
Person personToInsert=new Person("William")
personToInsert.save()

You are better off to write a script that adds the proper Hibernate objects to the production database instead of trying to use an SQL dump from your test database. Your script may do something like the following. Get a list of all people. For each person in the list create a new object with the necessary fields set such as name, age, etc. Save that object to the database. After the people are inserted add any objects associated with each person such as employee information.

Jared
A: 
  1. Fetch all Person objects in a List, using the test db configuration
  2. Serialize that list using ObjectOutputStream (or apache commons-lang SerializationUtils) to hard-disk
  3. Change the db configuration for the production db
  4. Deserialize the List (again, using ObjectInputStream or SerializationUtils)
  5. Iterate it save each person, but set the id to 0 before that:

    for (List<Person> person : personsList){
        person.setId(0);
        em.persist(person);
    }
    
  6. At best put the above functionality in a separate program that you can run whenever needed.

Bozho