Search code examples
springjsfmanaged-bean

How to use spring DAO methods with Managedbean object?


I have this ManagedBean:

@ManagedBean(name="studentItem")
@ViewScoped 
public class StudentBean implements Serializable {

    private static final long serialVersionUID = 1L;

    @ManagedProperty("#{StudentService}")
    private StudentService studentService;

    private int regId;
    private String firstName;
    private String lastName;

    //getters and setters


    public void saveStudent(StudentBean student) {
        //calling from xhtml to save form data

        studentService.addStudent(student);
    }
}

and this service implementation:

@Component
@Service("StudentService")
public class StudentServiceImpl implements StudentService {
    @Autowired
    private UserDao<Student> studentDao;
    @Override
    @Transactional
    public void addStudent(StudentBean student) {
         Student stu=new Student();
         stu.setRegId(student.getRegId());
         stu.setFirstName(student.getFirstName());
         stu.setLastName(student.getLastName());
         studentDao.addItem(stu);
    }
}

as you can see, I had to convert my StudentBean managed-bean object to Student object type to save it in database using DAO methods. Is there any standard way other than ugly copying properties one by one?


Solution

  • You are violating the MVC (Model View Controller) pattern! You have 3 parts (the Model=Student, the View (your facelet) and the Controller=StudentBean) which should be independent.

    If I were you I'll proceed like this:

    @ManagedBean(name="studentItem")
    @ViewScoped 
    public class StudentBean implements Serializable {
      private Student currentStudent;
      //getter/setter 
    
      @ManagedProperty("#{StudentService}")
      private StudentService studentService;      
    
      public String renderStudentForm(){
        //create a new student when you load the form
        currentStudent = new Student();
      }
    
      public void saveStudent(){
        studentService.addStudent(currentStudent);
      }
    }
    

    In your form view you can call student properties using EL #{studentItem.currentStudent.name}

    You got the idea.