开发者

Spring-Hibernate One to many relationship persistence

开发者 https://www.devze.com 2023-04-05 13:48 出处:网络
we have Three tables People(id, name), Registrations(id, p_id, sub_id,sem, date), Subjects(id,name, instructor)... I want to know what is the correct layer to write logic to persist list of Registrat

we have Three tables People(id, name), Registrations(id, p_id, sub_id,sem, date), Subjects(id,name, instructor)... I want to know what is the correct layer to write logic to persist list of Registration objects to the db? I mean currently I have following code in ResitrationController class..

@RequestMapping(..)
public String addRegistrations(@RequestParam(value="personId", required=true) int personId, @RequestParam(value="subjectIdList", required=true) List<Integer> subjectIdList){

 List<Registrations> reg开发者_StackOverflowistrationList = new ArrayList<Registrations>();

 for(int subjectId : subjectIdList){

     Registration registration = new Registration();
     registration.setSem("fall-11");
     registration.setDate(new Date());
     registration.setPerson(personService.getPersonById(personId));
     registration.setSubject(subjectService.getSubjectById(subjectId));

     registrationList.add(registration);
}
registrationService.addRegistrations(registrationList);
}

RegistrationService's addRegistration method just calls the same method on RegistrationDao RegistraionService(){ @Autowired REgistraionDao regDao;

    @Transactional
    addRegistration(registrationList){
         regDao.addRegistration(registrationList);         
    }
  }

   RegistrationDao(){
    @Autowired SessionFactory sessionFactory;

    addRegistration(registrationList){
          for(Registration registration: registrationList){
              sessionFactory.getCurrentSession().save(registration);
          }
    }
    }

I want to know if it is a correct way to have this logic in the controller method or to be shifted to some other place? I really want to send a list of registrations to the RegistrationService method because I would like the entire transaction to roll back even if one of the objects is not persisted.. thanks


Is the code above working? Is it working but it is not transactional?

In any case, I believe that you should add managed objects in the registrationList. So, they need to be persisted and flashed before calling the add() method. This should be done inside a transaction. So in my opinion you would better do that inside some "manager" class. that would be an extra leyer between the controller and your DAOs, or probably your service classes (it depends what you use your service layer for).

0

精彩评论

暂无评论...
验证码 换一张
取 消