Setting ID for foreign key
I have two tables:
Categories (id, name, abbr)
Project (id, name, categori开发者_高级运维esID)
The relationship is one to many (1 Categories to Many Projects). I use Hibernate DAOs and Mapping to store the data in the database. First, I store the data of Categories and for the Project table, I want the categoriesID to refer to the right id in Categories table.
For example, there are three categories in the database: Type1, Type2, Type3. Each of the Type has its own ID automatically assigned. Let say, Project1 is of Type2. How to set the categoriesID in Project table to refer to the id in Categories table of Type2 ?
I've set the foreign key in Project table to refer to the id in Categories table. My main has something like this (the data is extracted from a XML file) :
Session session = factory.getCurrentSession();
Transaction transaction = session.beginTransaction();
ECategories eCats = information.getCategories();
for(int i=0; i<eCats.getCategory().size(); ++i) {
ECategory category = eCats.getCategory().get(i);
Categories aCats = new Categories();
aCats.setName(category.getName());
aCats.setDescription(category.getDescription());
aCats.setAbbreviation(category.getAbbreviation());
aInformation.getCategorieses().add(aCats);
}
for (int i=0; i<information.getProjects().getProjectt().size();++i){
EProject project = information.getProjects().getProject().get(i);
Project aProject = new Project();
aProject.setName(project.getName());
aCats.getProjects().add(aProject);
aInformation.getProjects().add(aProject);
}
infDAO.attachDirty(aInformation);
transaction.commit();
The POJOs and mapping are generated by Hibernate. Currently, what was stored as the categoriesID for all the Projects are the last record stored in the categories table which makes it all the same category. What I wanted is the Project to refer to the correct categoriesID. How can I do that? I still couldn't figure the concept out. Anyone can help? thanks.
精彩评论