对于JSF和JPA来说有些新东西我在很大程度上依赖于Netbeans自动生成的代码来创建实体,外观和托管bean。我有一个User表,其中包含几个与County,Country等相关的嵌套子表,并且应用了通常的约束。
一切顺利,直到我开始创建一个JSF页面,使用DataTable构造显示数据库中的所有用户。我正在尝试将数字FK值替换为子表中引用的文本数据。 JSF框架默认显示此数据,因为它“知道”countryID字段是外键,但我知道countryID实际上包含Country对象,因此包含我想要的数据。我似乎无法找到正确的EL语法来提取和显示CountryID引用的Country对象中的CountryNAME字段。我确信信息已经存在,但我认为我没有问正确的问题......
用户实体(简化摘录):
@Entity
@Table(name = "Users")
@XmlRootElement
public class Users implements Serializable {
....=
@JoinColumn(name = "Country_ID", referencedColumnName = "Country_ID")
@ManyToOne(optional = false)
private Country countryID;
...
国家实体(简化):
@Entity
@Table(name = "Country")
@XmlRootElement
...
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "Country_ID")
private Integer countryID;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 45)
@Column(name = "Country_NAME")
private String countryNAME;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "countryID")
private Collection<User> userCollection;
...
JSF托管bean(摘录):
@Named("userController")
@SessionScoped
public class UserController implements Serializable {
private User current;
private DataModel items = null;
@EJB
private jpa.session.UserFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
...
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
@Override
public int getItemsCount() {
return getFacade().count();
}
@Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
....
JSF页面:
<h:dataTable value="#{userController.items}" var="item" border="0" cellpadding="2" cellspacing="0" rowClasses="jsfcrud_odd_row,jsfcrud_even_row" rules="all" style="border:solid 1px">
...
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListUserTitle_countryID}"/>
</f:facet>
<h:outputText value="#{item.countryID.countryID}"/>
</h:column>
...
答案 0 :(得分:-2)
覆盖国家/地区实体中的toString
()方法。默认情况下,它将返回Object的哈希码。如果您想要国家/地区名称,请按以下方式设计toString()
方法。
@Override.
public String toString(){
return countryNAME;
}
或强>
在EL表达式中调用countryName
。
<h:outputText value="#{item.countryID.countryNAME}" />