如何对 Managedbean 对象使用 spring DAO 方法?

How to use spring DAO methods with Managedbean object?

我有这个 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);
    }
}

和此服务实施:

@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);
    }
}

如您所见,我必须使用 DAO 方法将我的 StudentBean 托管 bean 对象转换为 Student 对象类型以将其保存在数据库中。除了丑陋的逐个复制属性之外,还有其他标准方法吗?

在这种情况下,有一些实用程序可以帮助您。 您可以尝试 BeanUtils 复制属性或 DozerMapper

您违反了 MVC(模型视图控制器)模式! 您有 3 个部分(Model=Student、View(您的 facelet)和 Controller=StudentBean),它们应该是独立的。

如果我是你,我会这样做:

@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);
  }
}

在您的表单视图中,您可以使用 EL 调用学生属性 #{studentItem.currentStudent.name}

你明白了。