本文介绍了如何将Spring DAO方法与Managedbean对象一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个ManagedBean:

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

以及此服务的实现:

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

如您所见,

我必须将我的StudentBean受管bean对象转换为Student对象类型,才能使用DAO方法将其保存在数据库中.除了丑陋地逐一复制属性之外,还有其他标准方法吗?

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?

推荐答案

您违反了MVC(模型视图控制器)模式!您具有3个部分,它们应该是独立的(模型=学生,视图(您的面)和控制器=学生Bean).

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

在表单视图中,您可以使用EL #{studentItem.currentStudent.name}

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

您明白了.

这篇关于如何将Spring DAO方法与Managedbean对象一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 12:48