如何为具有复合主键的实体编写转换器?
我想用URl编辑实体,例如' edit_representative.xhtml ? emp_id = 12345, project_id = 45
我用的是Omnifaces对于单主键
<o:viewParam name="emp_id" value="#{projectRepEdit.projectRep}"
converter="#{projectRepConverter}"
converterMessage="Bad request. Unknown Project Representative." required="true"
requiredMessage="Bad request. Please use a link from within the system." />
但是我如何将员工正在处理的project_id传递给转换器
编辑
根据BalusC的回答,我使用了第二个选项,并在我的projectRepConverter
转换器中有以下内容
String project_id = (String) component.getAttributes().get("project_id");
String emp_id= (String) component.getAttributes().get("emp_id");
ProjectRep prjRep = prjRepRepository.getByEmpIdAndProjectId(emp_id,project_id);
return prjRep;
和facelets
<f:metadata>
<o:viewParam name="project_id" value="#{projectRepEdit.project}"
converter="#{projectConverter}"
converterMessage="Bad request. Unknown Project." required="true"
requiredMessage="Bad request. Please use a link from within the system." />
<o:viewParam name="badge" value="#{projectRepEdit.projectRep}"
converter="#{projectRepConverter}"
converterMessage="Bad request. Unknown Project Rep." required="true"
requiredMessage="Bad request. Please use a link from within the system.">
<f:attribute name="project_id" value="#{param.project_id}" />
<f:attribute name="emp_id" value="#{param.emp_id}" />
</o:viewParam>
<f:viewParam>
和<o:viewParam>
不支持多参数。您需要手动获取参数。我可以想到两种基本方法:
-
在转换器中获取它作为请求参数:
String project_id = FacesLocal.getRequestParameter(context, "project_id");
-
或者将其作为组件属性传递:
<o:viewParam ...> <f:attribute name="project_id" value="#{param.project_id}" /> </o:viewParam>
这样你就可以在转换器中按如下方式获取它:
String project_id = (String) component.getAttributes().get("project_id");
选择哪种方式取决于转换器的预期可重用性。例如,您可以使用第二种方法将project_id
属性名称重命名为compound_key
左右,并使其可重用。