how get attribute relation from another entity class Java Persistance API and show to JSP through servlet? - class

I have 2 entities are entities meeting and meetingAgenda.
I write code entity class (EJB) from database like this.
public class Meeting implements Serializable {
......
#XmlTransient
public Collection<MeetingAgenda> getMeetingAgendaCollection() {
return meetingAgendaCollection;
}
public void setMeetingAgendaCollection(Collection<MeetingAgenda> meetingAgendaCollection) {
this.meetingAgendaCollection = meetingAgendaCollection;
}
.......
}
and entity class meeting agenda like this.
.....
public class MeetingAgenda implements Serializable {
....
public String getAgenda() {
return agenda;
}
public void setAgenda(String agenda) {
this.agenda = agenda;
}
....
}
method getMeetingAgendaCollection is a relation from meeting entity . then, in my controller servlet i call EJB like this.
public class ControllerServlet extends HttpServlet {
#EJB
private RapatFacadeLocal rapatFacade;
public void init() throws ServletException {
// store category list in servlet context
getServletContext().setAttribute("meetings", rapatFacade.findAll());
}
......
i want to show data from table entities meeting and meetingAgenda...but i can't..
please help..
i write code in JSP page.. like this..
<c:forEach var="meeting" items="${meetings}">
<td> MeetingCode : ${meeting.meetingCode} </td>
<td> Meeting : ${meeting.meeting} </td>
<td> Agenda : ${meeting.getMeetingAgendaCollection} </td>
</c:forEach>
how do I display data Agenda using getMeetingAgendaCollection ????
thanks for your help.

I finally found the solution,
in my controller servlet
Rapat selectedMeeting = rapatFacade.find(Long.parseLong(id));
request.setAttribute("meetingDetails",selectedMeeting);
Collection<RapatAgenda> agenda = selectedMeeting.getRapatAgendaCollection();
request.setAttribute("meetingAgendas", agenda);
in my JSP client
....
<c:forEach var="agenda" items="${meetingAgendas}">
<td> ${agenda.agenda} </td>
</c:forEach>
...
but I found the problem further.
if I want to display another entity (one to many) that relate to entities meeting.
i write code like this.
Rapat selectedMeeting = rapatFacade.find(Long.parseLong(id));
request.setAttribute("meetingDetails",selectedMeeting);
Collection<RapatAgenda> agenda = selectedMeeting.getRapatAgendaCollection();
request.setAttribute("meetingAgendas", agenda);
Unit selectUnit = unitFacade.find(selectedMeeting.getUnitInisiatorId());
request.setAttribute("initiator", selectUnit);
i wont selectedMeeting.getUnitInisiatorId() value is integer ,
if i write manually,
Unit selectUnit = unitFacade.find(Long.parseLong(1));
request.setAttribute("initiator", selectUnit);
problem solved..
what selectedMeeting.getUnitInisiatorId() syntax is correct ..?
please help.. thank you..

Related

Dynamic form with multiple objects submission in Spring?

I have an Object CreateProjectFormModel as follows (I am using Spring 4).
public class CreateProjectFormModel {
private Project project;
private List<DUser> users;
public CreateProjectFormModel() {
this.project = new Project();
this.users = new ArrayList<DUser>();
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public List<DUser> getUsers() {
return users;
}
public void setUsers(List<DUser> users) {
this.users = users;
}
}
I am not able to figure out how to create Controller and a corresponding form so that multiple DUser can be submitted at once - can do it if the object does not consist of a collection?
Read this, but I don't know how may users will be added to the project in advance, so cannot fix the users size.
I read through thymeleaf tutorial, but would be interested to know if can do without use of thymeleaf.
Thanks.
The link you posted in the question List<Foo> as form backing object using spring 3 mvc, correct syntax? should provide a solution for you, what is discussed in the comments
I assume that this solution requires having a fixed amount of input
fields, is that correct? What if you have a dynamic number of input
fields?
does not concern the number of users, which doesn't have to be fixed, rather it concerns the fact that that the properties of the object is differing, which I don't believe is your case. So, if your DUser has a property userName, and e.g. your Project has a property name. Your controller method could simply be,
#RequestMapping(value = "/test", method=RequestMethod.POST)
public String processSubmit(CreateProjectFormModel createProjectFormModel) {
...
}
and your form
<form:form action="/form/test" method="post">
<div class="single">
<input type="text" name="project.name"/>
<input type="text" name="users[0].userName"/>
add another user
<input type="submit" value="Save">
</div>
</form:form>
where you will have to provide some effort is to create a javascript function addNewUserInputSection that will add new set of input fields for the users property with an incremented index, e.g.
<form:form action="/form/test" method="post">
<div class="single">
<input type="text" name="project.name"/>
<input type="text" name="users[0].userName"/>
<input type="text" name="users[1].userName"/>
add another user
<input type="submit" value="Save">
</div>
</form:form>
the examples are basic, but should be enough to have you resolve your issue
Although the above answer works, here's an alternate that does not require you to create a wrapper class/ form class.
Model And Controller
public class Foo {
private String name;
private List<Foo> fooList;
public Foo() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFooList() {
return fooList;
}
public void setFooList(String fooList) {
this.fooList = fooList;
}
}
#Controller("/")
public class FooController{
//returns the ModelAttribute fooListWrapper with the view fooForm
#RequestMapping(value = "/FOO", method = RequestMethod.GET)
public String getFooForm(Model model) {
List<Foo> fooList = service.getFooList();
model.addAttribute("fooList", fooList);
return "list_foo"; //name of the view
}
#RequestMapping(value = "/FOO", method = RequestMethod.POST)
public String postFooList(#ModelAttribute("foo")Foo foo, Model model) {
List<Foo> list = foo.getFooList(); // **This is your desired object.
//If you debug this code, you can easily find this is the list of
//all the foo objects that you wanted, provided you pass them properly.
//Check the jsp file to see one of the ways of passing such a list of objects**
//Rest of the code
}
}
JSP View
<form:form id="form" action="<paste-target-url-here>" method="POST" modelAttribute="fooList">
<c:forEach items="${fooList}" varStatus="i">
<form:input path="fooList[${i.index}].name" type="text"/>
<!-- Here you are setting the data in the appropriate index which will be caught in the controller -->
</c:forEach>
<button>submit</button>
</form:form>

Primefaces Datatable filterOption in columns

I have a database table displayed through Datatable (Primefaces 3.4.2) and I want to show a comboFilter in the header populated with values from the database table itself.
1) Since these values are not a PK or FK, I built a named query to retrieve distinct values for the prefDep column:
#NamedQuery(name = "Upb.findPrefDeps", query = "SELECT DISTINCT u FROM Upb u WHERE u.prefDep = :prefDep")
2) In my AbstractController:
public List<T> getPrefDepsList() {
if (prefDeps == null) {
prefDeps = this.ejbFacade.findPrefDeps();
}
return prefDeps;
}
3) As I inject the facade EJB, how can I build a managed bean property to be used in the filterOption below?
The managedBean:
#ManagedBean(name = "upbController")
#ViewScoped
public class UpbController extends AbstractController<Upb> implements Serializable {
#EJB
private UpbFacade ejbFacade;
public UpbController() {
super(Upb.class);
}
#PostConstruct
public void init() {
super.setFacade(ejbFacade);
}
public SelectItem[] getPrefDepOptions() {
return prefDepOptions; //build/populate this
}
}
The jsf:
<p:column filterBy="prefdep" headerText="PrefDep"
filterOptions="#{upbController.prefDepOptions}"
filterMatchMode="exact">
<h:outputText value="#{item.prefDep}" />
</p:column>
Thanks in advance.
I do not know if I understand your question the right way. You want to execute the named query once and store the distinct values in a property in the managed bean? For that you can use a PreRenderView event which would be called before rendering the page. You can call a init-function to load such values with this event.
You can also access the getter with the named query, but this may be called not only once.

Play! Framework 2.X, form handling

I am new to using Play! Framework 2.X and have a simple question.
How can i send to my method Job.create(filledJob) a fully set Job object? Meaning that Company object including in Job object is filled too.
I have the following:
public class Job {
public String title;
public Company company;
}
public class Company {
public String name;
public String email;
}
I have a form in my template, containing a Job information section and a Company section
#(jobForm: Form[Job], companyForm: Form[Company])
#form(routes.Application.newJob()) {
#inputText(jobForm("title"))
#inputText(companyForm("name"))
<input type="submit" value="Create">
}
My controller(Application.java) looks like that:
public class Application extends Controller {
static Form<Job> jobForm = form(Job.class);
static Form<Company> companyForm = form(Company.class);
public static Result index() {
return ok(
views.html.index.render(jobForm, companyForm)
);
}
public static Result newJob() {
Form<Job> filledForm = jobForm.bindFromRequest();
Job.create(filledForm.get());
return redirect(routes.Application.index());
}
}
Ideally, i would like to send to my method Job.create(job), with job with all the fields set (string job title as well as Company object). It must be a numpty question, i appologize for that. Any help would be greatly appreciated
Many thanks
You can't use #inputText(companyForm("name")) if you want bind the form directly into object, but instead you can use a select form helper for selecting the company, check ie. computer-database sample it's quite similar case...
On the other hand if you have a lot of companies and don't want to create huge select consider another scenario: just instead route like /job/new use /company/:companyId/add-job in other words just you'll send a form and bind it from request + additionaly will get Company by id in route param and will add to object, pseudo code:
public static Result addJobToCompany(Integer companyId){
Job job = form(Job.class).bindFromRequest().get();
job.company = Company.find.byId(companyId);
job.save();
return redirect(routes.Application.jobDetails(job.id));
}
Ok i am replying to my own question as i must not have explained my question clearly.
To make it simple : I needed to set the Company object from a form. Find below my solution
Hope it will help you.
public class Job {
public String title;
#Valid
public Company company;
}
public class Company {
public String name;
public String email;
}
#(jobForm: Form[Job], companyForm: Form[Company])
#form(routes.Application.newJob()) {
#inputText(jobForm("title"))
#inputText(jobForm("company.name"))
<input type="submit" value="Create">
}

JPA EAGER fetch works only if server is restarted

Good evening everybody, this is my first post on Stack Overflow.
I have been quite recently introduced to Java 6 EE and, in particular, to JPA as part of the JSF 2.1 framework and I am now facing a strange behavior that I would like you to help me understand.
In our project (developed using NetBeans 7.2) we have several one-to-many relationship and we would like to navigate them the same way we navigate many-to-one ones. The fact is that, instead, we are able to make them work as we want only after having restarted the application server (Glassfish 3.1.2) and, in addition, this behavior lasts only till the next deployment; which means we need to restart Glassfish every time we apply a modification...
Here are some code excerpts to help you understand our situation.
This represents our main entity (Person) that has, among the others, a one-to-many relationship with Email as well as with Phone and a many-to-one relationship with AccountType
#Entity
public class Person implements Serializable {
//
//private non-collection fields including id
//
#OneToMany(mappedBy="person", fetch=FetchType.EAGER)
private Collection<Email> personEmails;
#OneToMany(mappedBy="person")
private Collection<Phone> personPhones;
#ManyToOne
private AccountType accountType;
//
// getter and setter, hashCode, isEqual and toString
//
}
And these are Email...
#Entity
public class Email implements Serializable {
//
//private non-collection fields including id
//
private String address;
#ManyToOne
private Person person;
//
// getter and setter, hashCode, isEqual and toString
//
}
... Phone ...
#Entity
public class Phone implements Serializable {
//
//private non-collection fields including id
//
private String number;
#ManyToOne
private Person person;
//
// getter and setter, hashCode, isEqual and toString
//
}
... and AccountType
#Entity
public class AccounType implements Serializable {
//
//private non-collection fields including id
//
private String name;
#OneToMany(mappedBy="accountType")
private Collection<Person> persons;
//
// getter and setter, hashCode, isEqual and toString
//
}
We have then set up a sample page to test how that three fields in Person are actually fetched.
This represents the xhtml page...
<h:form id="form">
<h:panelGrid columns="2">
<h:outputLabel value="forename" />
<h:outputLabel value="#{meBean.currentUser.forename}" />
<h:outputLabel value="emails" />
<h:outputLabel value="#{meBean.currentUser.personEmails.size()}" />
<h:outputLabel value="phones" />
<h:outputLabel value="#{meBean.currentUser.personPhones}" />
<h:outputLabel value="accountType" />
<h:outputLabel value="#{meBean.currentUser.accountType.name}" />
</h:panelGrid>
</h:form>
... and this the controller
#ManagedBean
#RequestScoped
public class MeBean {
#EJB
private PersonFacade personFacade;
private Person currentUser;
public MeBean() {
init();
}
#PostConstruct
private void init() {
// Hard-coding user details
try {
this.currentUser = this.personFacade.getFromUsername("user1");
this.currentUser.getPersonPhones().isEmpty();
} catch (Exception e) {
}
}
public Person getCurrentUser() {
return currentUser;
}
public void setCurrentUser(Person currentUser) {
this.currentUser = currentUser;
}
}
Now, the result we get is the one we expect only if we access the page right after having restarted the application server.
forename Alice
emails 2
phones {[sums.groupa.entities.Phone[id=38]]}
accountType Student
If we modify anything (except for the view) and save, after the inevitable deploy, the result is different.
forename Alice
emails 0
phones {[]}
accountType Student
Why is that happening and how can we avoid it?
Thanks in advance.
AG
A couple of contributors (that I want to thank for their quick replies) asked for the PersonFacade implementation.
public Person getFromUsername(String username)
{
try
{
Query q = em.createQuery("SELECT p FROM Person p LEFT JOIN FETCH p.personEmails WHERE UPPER(p.username) = :username");
q.setParameter("username", username.toUpperCase());
return (Person) q.getSingleResult();
}
catch (Exception ex)
{
Logger.getLogger(PersonFacade.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
As you can see I tried to use FETCH JOIN as suggested but the query is getting out too many results: it should fetch only one instance of Person representing Alice and containing two instances of Email in the personEmails field but I suspect it is getting two different instances of Person, each having a different instance of Email attached.
The original query was as follows:
SELECT p FROM Person p WHERE UPPER(p.username) = :username
Thanks again.
AG
I don't know how you wrote your personFacade and got the Person entity.
But I guess you used query.
If you are using JPQL, try fetch join.

How do I bind to a class that is not in my model in asp.net mvc 2?

Normally when I design a form, the data I am expecting is part of the viewmodel for the page, and I can put the class in the controller method and the binding works.
However, I am adding a form in a partial view of a master page, so it is not specific to any one viewmodel. I tried just making sure the ID of the form field would match up with what would have normally automatically been generated, but the object values are always null in my controller method.
Here is a snippet form my the partial view of my master page:
<tr>
<td >Current password:</td>
<td><%= Html.Password("PasswordChange.OriginalPassword", "", new RouteValueDictionary { { "class", "required remote" } })%></td>
</tr>
<tr>
<td >New password:</td>
<td><%= Html.Password("PasswordChange.NewPassword", "", new RouteValueDictionary { { "class", "required remote" } })%></td>
</tr>
As you can see can imagine, PasswordChange is not a part of all of my view models (surely it's not necessary to inherit all of my viewmodels from a common base in order to use this form?).
My controller method looks like this:
[HttpPost]
public ActionResult ChangePassword(PasswordChange PasswordChange)
{
I hit the method, but PasswordChange.OriginalPassword and PasswordChange.NewPassword are always null.
I assume there is some easy way to do this, but I cannot figure it out.
Get rid of the prefixes:
<tr>
<td>Current password:</td>
<td><%= Html.Password("OriginalPassword", "", new RouteValueDictionary { { "class", "required remote" } })%></td>
</tr>
<tr>
<td >New password:</td>
<td><%= Html.Password("NewPassword", "", new RouteValueDictionary { { "class", "required remote" } })%></td>
</tr>
or if you want to keep a prefix, make sure you define this prefix:
[HttpPost]
public ActionResult ChangePassword(
[Bind(Prefix = "PasswordChange")] PasswordChange model
)
{
...
}
By the way you might also consider using child actions instead:
public class PasswordChangeController: Controller
{
[ChildActionOnly]
public ActionResult Index()
{
var model = new PasswordChange();
return PartialView(model);
}
}
and then inside your masterpage instead of rendering a partial, render the child action:
<% Html.RenderAction("Index", "PasswordChange"); %>
and of course now you will have a strongly typed ~/Views/PasswordChange/Index.ascx partial where you could generate your form and use the strongly typed versions of the helpers.
For more information about child actions you may take a look at Phil Haack's blog post on this topic.
My PasswordChange class's member's were not set as public.
#%$#$^#%&%
from
public class PasswordChange
{
public OriginalPassword { get; set; }
public NewPassword { get; set; }
}
to
public class PasswordChange
{
public string OriginalPassword { get; set; }
public string NewPassword { get; set; }
}