I'm looking for good practices and clean solution to my problem. There are 2 entity classes:
@Entity
public class Site implements Serializable {
...
@OneToMany(mappedBy = "site")
private List<SiteIp> siteIpList;
...
public List<SiteIp> getSiteIpList() {
return siteIpList;
}
public void setSiteIpList(List<SiteIp> siteIpList) {
this.siteIpList = siteIpList;
}
}
@Entity
@IdClass(SiteIpPK.class)
public class SiteIp implements Serializable {
@Id
@ManyToOne(fetch = FetchType.LAZY)
private Site site;
@Id
private int idx;
private String ip;
/* other stuff such as constructors, getters and setters */
}
SiteIpPK has 2 columns, it should be clean :) Obviously, this is commonly used model in world.
Next, there is a view layer. JSF page has 3 fields showing SiteIp.ip for given site and idx. As far, I've wrote helper getter method on Site entity:
public String getIpForIdx(Integer idx) {
// there's no simple siteIpList.get(idx), because of additional logic in getter
// so let's iterate through entire list
for (SiteIp siteIp : this.siteIpList) {
if (/* other logic returns true value && */ siteIp.getIdx() == idx) {
return siteIp.getIp();
}
}
return null;
}
JSF expression language is constructed as follows:
<h:inputText id="sync1_ip" value="#{siteController.editContext.site.getIpForIdx(1)}" />
Now, when page is accessed, proper IP values is propagated to input text field, as far it's all good. But, when IP changed and form is submitted, EL throws exception:
javax.el.PropertyNotWritableException: /edit/siteEdit.xhtml @47,123 value="#{siteController.editContext.site.getIpForIdx(1)}": Illegal Syntax for Set Operation
I understand and acknowledge that, so there is my question:
What are best practices to handle this issue? Somewhat awful solution is to write as many helper methods as unique indexes exists:
public String getIp1() {
return this.IpForIdx(1);
}
public String getIp2() {
return this.IpForIdx(2);
}
/* ... */
public void setIp1(String newIp) {
this.siteIpList.add(1, newIp);
}
public void setIp2(String newIp) {
this.siteIpList.add(2, newIp);
}
/* ... and so on... */
with JSF EL:
<h:inputText id="sync1_ip" value="#{siteController.editContext.site.ip1}" />
Are there other, more flexible and beautiful solutions?