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
.
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 shoul开发者_运维问答dn't have to redo all the effort just to change the id's that my s/w should ideally be doing..
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.
- Fetch all
Person
objects in aList
, using the test db configuration - Serialize that list using
ObjectOutputStream
(or apache commons-langSerializationUtils
) to hard-disk - Change the db configuration for the production db
- Deserialize the
List
(again, usingObjectInputStream
orSerializationUtils
) Iterate it save each person, but set the id to 0 before that:
for (List<Person> person : personsList){ person.setId(0); em.persist(person); }
At best put the above functionality in a separate program that you can run whenever needed.
精彩评论