When or where do entities get created?
Do they get created when the XHTML page loads and accesses the entities via the managed bean?
Or do they get automatically created in the managed bean?
Do we need to manually create it from the managed bean’s constructor?
Please see the code below (some necessary code might not have been copied.)
The entity would be:
public class PersonalInfo implements Serializable {
@Size(max = 50)
@Column(name = "FIRST_NAME", length = 50)
private String firstName;
// some getters and setters
}
the web page would be:
<h:form>
<h:outputText value="first name"/>
<h:inputText value="#{personalInforController.personalInfo.firstName}" />
<h:commandButton value="hit me"
action="#{personalInforController.create}"
immediate="true"/>
</h:form>
and the backing bean would be:
@Named(value = "personalInfoController")
@SessionScoped
public class PersonalInforController {
@EJB
PersonalInfoFacade ejbFacade;
PersonalInfo personalInfo;
String defaultPage = "index";
public String create() {
try {
ejbFacade.create(personalInfo);
return "prepareCreate";
} catch (Exception e) {
return "success";
}
}
}
In the example code given, the
createaction indeed doesn’t seem to be able to work. The entity must be created by the backing bean before that.If it’s a simple entity, either the constructor or an @PostConstruct method would work. For instance:
Some notes about the code. It’s highly suspicious, and most likely plain wrong, to declare your bean to be @SessionScoped. If
personalInfois being edited in two tabs or windows you’ll be in a world of hurt. I suggest making your bean @ViewScoped (for CDI, there’s a separate extension made by the Seam3 that enables this, if you can’t/won’t use this extension consider using @ManagedBean instead of @Named).Also, you might want to declare your instance variables to be private and give
ejbFacadea better name (e.g. personalInfoFacade). I also doubt whetherimmediateis necessary on the commandButton, and since the outputText is obviously a label for the given inputText, you might want to consider using outputLabel and the for attribute.