Display Data from multiple tables - jsf

I'm new with JSF / Java and relational DB queries.
I'm trying to Display data from two tables in one datatable.
I have two tables tblUser and tblCity.
For These tables I've got two models Users and City.
Also got a UserDAO and a UserController.
I'd like to know how to select user data from tblUser and select City data from tblCity and Display them on my view. With MVC style.
Model:
public class User{
private Integer user_id;
private String user_name;
private Integer City_id;
//getter and setter
...
}
public class City{
private Integer city_id;
private String city_name;
//getter and setter
...
}
My Controller
#ManagedBean
#SessionScoped
public List<User> showUser(){
List<User> users = new ArrayList<>();
users= userDAO.showUserList();
return users;
}
My DAO
#ManagedBean
#RequestScoped
public class userDAO{
/**
* Creates a new instance of patientDAO
*/
private final connectToDB con = new connectToDB();
public userDAO() {
}
public List<User> showUserList() {
Connection dbConnection = null;
dbConnection = con.getDBConnection();
PreparedStatement pstmt = dbConnection
.prepareStatement("select a.user_id, a.user_name, b.city_name"
+ " from users a, cities b WHERE a.city_id = b.city_id");
ResultSet rs = pstmt.executeQuery();
List<User> users = new ArrayList<>();
List<City> cities = new ArrayList<>();
while (rs.next()) {
User user = new User();
City city = new City();
user.setUser_Id(rs.getInt("user_id"));
user.setUser_Id(rs.getString("user_name"));
city.setCity_Name(rs.getInt("city_name"));
users.add(user);
cities.add(city);
}
// close resources
rs.close();
pstmt.close();
dbConnection.close();
return users;
}
}
My View
<p:dataTable id="userDT" var="user" value="#{userController.showUserList()}">
<p:column width="200" headerText="User Name">
<h:outputText value="#{user.user_name}" />
</p:column>
<p:column width="200" headerText="City Name">
<h:outputText value="#{...}" />
</p:column>
</p:dataTable>

Supposing that one User has one City, you can add a city attribute to the User class:
public class User{
...
private City city;
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
...
}
In your userDAO, at the end of the while loop of the showUserList() method, put the city in the user object:
...
while (rs.next()) {
User user = new User();
City city = new City();
user.setUser_Id(rs.getInt("user_id"));
user.setUser_Id(rs.getString("user_name"));
city.setCity_Name(rs.getInt("city_name"));
user.setCity(city);
users.add(user);
}
...
The list of cities in the showUserList() method is not used outside the method, you can delete it.
And finally, edit the view like this:
...
<p:column width="200" headerText="City Name">
<h:outputText value="#{user.city.city_name}" />
</p:column>
...

Related

one to one mapping Entity class from dataBase using netbeans jpa

jsf single dataTable. I want to get the values from database table column from different entity class. One entity class is IASLABELS primary key is LANG_NO and LABELS_NO and another entity class is LANGDEF primary key is LANG_NO.
I need LANG_NAME in jsf dataTable column.
#Entity
#Table(name = "IAS_LABELS")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "IasLabels.findAll", query = "SELECT i FROM IasLabels i"),
#NamedQuery(name = "IasLabels.findByLangNo", query = "SELECT i FROM IasLabels i WHERE i.iasLabelsPK.langNo = :langNo"),
#NamedQuery(name = "IasLabels.findByLabelNo", query = "SELECT i FROM IasLabels i WHERE i.iasLabelsPK.labelNo = :labelNo"),
#NamedQuery(name = "IasLabels.findByCaptionDet", query = "SELECT i FROM IasLabels i WHERE i.captionDet = :captionDet"),
#NamedQuery(name = "IasLabels.findByTrnsFlg", query = "SELECT i FROM IasLabels i WHERE i.trnsFlg = :trnsFlg")})
public class IasLabels implements Serializable {
private static final long serialVersionUID = 1L;
// #OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
// #PrimaryKeyJoinColumn
// private LangDef langDef;
//
// public LangDef getLangDef() {
// return langDef;
// }
//
// public void setLangDef(LangDef langDef) {
// this.langDef = langDef;
// }
1) Answer :
You have 1st option with hibernate entity add foreign key primary key as per you database table and used my answer as gave yesterday
Datatable displaying 2 different entity tables with relation need to get the another column values from database table
2) Answer
Now you have Alternate option
1) you need to create normal class like following
public class IasLabelsWithLang implements Serializable {
private static final long serialVersionUID = 1L;
private IasLabels lasLabels;
private LangDef langDef;
public LangDef getLangDef() {
return langDef;
}
public void setLangDef(LangDef langDef) {
this.langDef = langDef;
}
public IasLabels getIasLabels() {
return iasLabels;
}
public void setIasLabels(IasLabels iasLabels) {
this.iasLabels = iasLabels;
}
}
2) you need to change following thing in your manage bean
#ManagedBean
#SessionScoped
public class LabelsMB {
static Logger logger = Logger.getLogger(LabelsMB.class);
List<IasLabelsWithLang> labelsList = null;
#ManagedProperty(value = "#{labelService}")
private LabelService labelService;
public LabelService getLabelService() {
return labelService;
}
public void setLabelService(LabelService labelService) {
this.labelService = labelService;
}
public List<IasLabelsWithLang> getListData() {
if (labelsList == null || labelsList.isEmpty()) {
if (this.getLabelService() != null) {
labelsList = this.getLabelService().getAllLabels();
}
}
return labelsList;
}
}
3) You need to following changes in your services class
#Service
#Transactional
public class LabelService {
static Logger logger = Logger.getLogger(LabelService.class);
#Autowired
private ILabelsDAO labelRepo;
#Autowired
private LangDefDAO langDefDAO;
public ILabelsDAO getLabelRepo() {
return labelRepo;
}
public void setLabelRepo(ILabelsDAO labelRepo) {
this.labelRepo = labelRepo;
}
public List<IasLabelsWithLang> getAllLabels() {
List<IasLabelsWithLang> list = new ArrayList<IasLabelsWithLang>();
if (this.getLabelRepo() != null) {
List<IasLabels> lasLabelsList = this.getLabelRepo().findAll();
for(IasLabels lasLabels : lasLabelsList){
IasLabelsWithLang model = new IasLabelsWithLang();
model.setIasLabels(lasLabels);
model.setLangDef(langDefDAO.findByPk(lasLabels.getLangNo()));
list.add(model);
}
return list;
}
return null;
}
public Iterable<IasLabels> saveData(List<IasLabels> originalValue) {
return labelRepo.save(originalValue);
}
}
4) You need to do in your XHTML file for flowing changes
<p:dataTable id="dataTable" emptyMessage="#{res.NO_RECORDS_FOUND}" var="lab" value="#{labelsMB.listData}" editable="true" editMode="cell" paginator="true" rows="10" paginatorTemplate=" {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" rowsPerPageTemplate="5,10,15">
<p:column headerText="#{res.CAPTION_DET}" sortBy="#{lab.lasLabels.captionDet}" filterBy="#{lab.lasLabels.captionDet}" filterMatchMode="contains" filterStyle="width: 360px;">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{lab.lasLabels.captionDet}" />
</f:facet>
<f:facet name="input">
<h:inputText value="#{lab.lasLabels.captionDet}" style="width:96%"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="#{res.LABEL_NO}" sortBy="#{lab.lasLabels.iasLabelsPK.labelNo}" filterBy="#{lab.lasLabels.iasLabelsPK.labelNo}">
<p:outputLabel value="#{lab.iasLabelsPK.labelNo}" />
</p:column>
<p:column headerText="#{res.LANGUAGE_NO}" sortBy="#{lab.lasLabels.iasLabelsPK.langNo}" filterBy="#{lab.lasLabels.iasLabelsPK.langNo}" width="100">
<p:outputLabel value="#{lab.iasLabelsPK.langNo}" />
</p:column>
<p:column headerText="#{res.LANGUAGE_NAME}" sortBy="#{lab.langDef.langName}" filterBy="#{lab.langDef.langName}" width="130">
<p:outputLabel value="#{lab.langDef.langName}" />
</p:column>
</p:dataTable>
Hope, you would be fix problem.. :)
EDITED
You need to add langNo variable inside your IasLabels entity
#Entity
#Table(name = "IAS_LABELS")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "IasLabels.findAll", query = "SELECT i FROM IasLabels i"),
#NamedQuery(name = "IasLabels.findByLangNo", query = "SELECT i FROM IasLabels i WHERE i.iasLabelsPK.langNo = :langNo"),
#NamedQuery(name = "IasLabels.findByLabelNo", query = "SELECT i FROM IasLabels i WHERE i.iasLabelsPK.labelNo = :labelNo"),
#NamedQuery(name = "IasLabels.findByCaptionDet", query = "SELECT i FROM IasLabels i WHERE i.captionDet = :captionDet"),
#NamedQuery(name = "IasLabels.findByTrnsFlg", query = "SELECT i FROM IasLabels i WHERE i.trnsFlg = :trnsFlg")})
public class IasLabels implements Serializable {
// langNo variable you need to add in your IasLabels entity
#Column(name = "LANG_NO")
private Short langNo;
public Short getLangNo() {
return langNo;
}
public void setLangNo(Short langNo) {
this.langNo = langNo;
}
}

Password field <p:password> Value Won't Re-Appear In Form After Saved And Selecting That Row From Data Table [duplicate]

This question already has an answer here:
p:password doesn't redisplay prefilled model value
(1 answer)
Closed 6 years ago.
So, I am taking in a password value from a form which is being saved to an object. The objects are saved to a data table. I have the functionality to allow a user to select a row from the data table, and the values for that object will be populated back into the form. Unfortunately, all values will populate except the password field. If I alter the password field to become an inputText, the value will be shown after selecting the row from the data table. Below is the code. Thanks.
HTML
Customer Registration
<p:panelGrid columns="2">
<p:commandButton value="Submit" image="ui-icon-check" ajax="false" actionListener="#{createPerson.createPerson()}"/>
</p:panelGrid><br/>
<p:panel id="table">
<p:dataTable id="dataTable" editable="false" var="person" paginator="true" rows="5" selectionMode="single"
value="#{createPerson.dataModel}" rowKey="#{person.id}">
<f:facet name="header">
Record
</f:facet>
<p:ajax listener="#{createPerson.processUserSelection}" event="rowSelect" update=":createPersonForm"/>
<p:ajax listener="#{createPerson.processUserUnselection}" event="rowUnselect" update=":createPersonForm"/>
<p:column sortBy="id" headerText="ID">
<h:outputText value="#{person.id}" />
</p:column>
<p:column sortBy="ssn" headerText="SSN">
<h:outputText value="#{person.ssn}" />
</p:column>
</p:dataTable>
</p:panel>
</h:form>
</h:body>
</html>
Person
public class Person {
private String ssn;
private String id;
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Create Person
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
#ManagedBean(name = "createPerson")
#SessionScoped
public class CreatePerson {
private Person person;
List<Person> personList = new ArrayList<>();
private PersonDataModel dataModel;
private static int id = 0;
public CreatePerson() {
person = new Person();
dataModel = new PersonDataModel(personList);
}
public String getSsn() {
return person.getSsn();
}
public void setSsn(String ssn) {
person.setSsn(ssn);
}
public void createPerson(){
System.out.println(" Submit Button clicked..");
System.out.println(" SSN: " + person.getSsn());
if (person.getId() == null || person.getId().equalsIgnoreCase("-1")) {
//New Person
person.setId("" + (id++));
personList.add(person);
person = new Person();
person.setId("-1");
}
else {
}
}
public void processUserSelection(SelectEvent evt) {
System.out.println(" Row selected from the Data Table .");
this.person = (Person) evt.getObject();
}
public void processUserUnselection(UnselectEvent evt) {
System.out.println(" Row unselected from the Data Table .");
this.person = new Person();
this.person.setId("-1");
}
public PersonDataModel getDataModel(){
return this.dataModel;
}
}
Data Table Class
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;
public class PersonDataModel extends ListDataModel<Person> implements SelectableDataModel<Person>{
public PersonDataModel() {
}
public PersonDataModel(List<Person> data) {
super(data);
}
#Override
public Person getRowData(String rowKey){
System.out.println("Key = " + rowKey);
List<Person> persons = (List<Person>) getWrappedData();
for (Person person : persons) {
if(person.getId().equals(rowKey)){
return person;
}
}
System.out.println("Valid Person not found");
return null;
}
#Override
public Object getRowKey(Person person){
return person.getId();
}
}
Its a high risk to display password ,if you will look into Primeface <p:password /> its a extension of JSF <h:inputSecret /> .
It have a attribute called redisplay by default its value should be false
Boolean flag indicating whether or not a previously entered password
should be rendered in form. Default is false.
Now add this attribute(redisplay="true") in your component.
For more information you can check Tag inputSecret
Render the clientId of the component as the value of the "name"
attribute. Render the current value of the component as the value of
the "value" attribute, if and only if the "redisplay" component
attribute is the string "true". If the "styleClass" attribute is
specified, render its value as the value of the "class" attribute.

datamodel must implement when selection is enabled.?

I wanted to remove rows from the data table when the checkbox is ticked and remove button is pressed..
This is the datatable snippet :
<p:dataTable id="cartTable" lazy="true" scrollable="true"
scrollHeight="115" selection="#{Cart_Check.selectedItems}"
value="#{Cart_Check.cart}" var="cart" rowKey="#{cart.sheetno}"
style="widht:100%;margin-top:10%;margin-left:1%;margin-right:30px ;box-shadow: 10px 10px 25px #888888;">
<f:facet name="header">
Checkbox Based Selection
</f:facet>
<p:column selectionMode="multiple" style="width:2%">
</p:column>
//Here the columns are metion
<f:facet name="footer">
<p:commandButton id="viewButton" value="Remove" />
</f:facet>
</p:dataTable>
This is the backing bean
public class checkcart {
private int items;
private ArrayList<User_Cart> cart;
private ArrayList<User_Cart> selectedItems;
public checkcart() {
getvalues();
}
//getter and setter
public void getvalues() {
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext()
.getSession(false);
System.out.println("Cart Request ::::" + session.getAttribute("regid"));
try {
Connection connection = BO_Connector.getConnection();
String sql = "Select * from cart_orderinfo where usrregno=?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, (String) session.getAttribute("regid"));
ResultSet rs = ps.executeQuery();
cart = new ArrayList<>();
while (rs.next()) {
User_Cart user_cart = new User_Cart();
user_cart.setSheetno(rs.getString("sheetno"));
user_cart.setState_cd(rs.getString("state_cd"));
user_cart.setDist_cd(rs.getString("dist_cd"));
user_cart.setLicensetype(rs.getString("license_type"));
user_cart.setFormat(rs.getString("sheet_format"));
user_cart.setQuantity(rs.getInt("quantity"));
cart.add(user_cart);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
and when i run this page i get the following error
datamodel must implement org.primefaces.model.selectabledatamodel when selection is enabled.
But when i remove the checkbox then their is no error but it is without a checkbox.
What to do and how to resolve the following error ..Kindly help..
I want something like this :
http://www.primefaces.org/showcase/ui/datatableRowSelectionRadioCheckbox.jsf
You just need to define ListDataModel as shown below,
public class SD_User_Cart extends ListDataModel<User_Cart> implements SelectableDataModel<User_Cart> {
public SD_User_Cart() {
}
public SD_User_Cart(List<User_Cart> data) {
super(data);
}
#Override
public User_Cart getRowData(String rowKey) {
//In a real app, a more efficient way like a query by rowKey should be implemented to deal with huge data
List<User_Cart> rows = (List<User_Cart>) getWrappedData();
for (User_Cart row : rows) {
if (row.getCartId.toString().equals(rowKey)) {//CartId is the primary key of your User_Cart
return row;
}
}
return null;
}
#Override
public Object getRowKey(User_Cart row) {
return row.get.getCartId();
}
}
Change your "cart" object into SD_User_Cart as shown below,
private SD_User_Cart cart;
Then define selection in p:datatable, and add a column as shown below,
<p:column selectionMode="multiple" style="width:18px"/>
Hope this helps:)
You need to define a your private ArrayList<User_Cart> selectedItems; data member in back class public class checkcart like this private User_Cart[] selectedItems; and give setter and getter method for the same it will work.
I had also faced same problem.

DataModel must implement org.primefaces.model.SelectableDataModel when selection is enabled.

I'm trying to create a DataTable with Multiple Row Selection but i'm getting an error here's the link of the tutorial http://www.primefaces.org/showcase/ui/datatableRowSelectionMultiple.jsf :
Here's my xhtml:
<p:dataTable border="1" value="#{projectAdminisrationMB.projectNoUsersList}"
var="userObj"
selection="#
{projectAdminisrationMB.selectedUsers}"
selectionMode="multiple" rowIndexVar="rowIndex"binding="#{table2}">
<p:column id="column3">
<f:facet name="header">
<h:outputText value=" user "></h:outputText>
</f:facet>
<h:outputText value="#{userObj.name}"/>
/
<h:outputText value="#{userObj.lastName}"></h:outputText>
<h:outputText value="#{userObj.firstName}"></h:outputText>
</p:column>
<f:facet name="footer">
<p:commandButton id="addProjectUser" value=" Add " onclick="dlg1.show()" />
<p:commandButton id="deleteProjectUser" value=" Delete " />
</f:facet>
</p:dataTable>
Managed Bean :
#ManagedBean
#SessionScoped
public class ProjectAdminisrationMB implements Serializable {
private static final long serialVersionUID = 1L;
private String projectName;
private List <User> projectUsersList;
private List<User> projectNoUsersList;
private List<User> selectedUsers;
private String projectAdmin;
public ProjectAdminisrationMB() {
super();
AdministrationProjectFinal administrationProjectFinal =new
AdministrationProjectFinal();
this.projectUsersList=administrationProjectFinal.getUserList();
this.projectNoUsersList=administrationProjectFinal.getNotUserList();
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public List<User> getProjectUsersList() {
return projectUsersList;
}
public void setProjectUsersList(List<User> projectUsersList) {
this.projectUsersList = projectUsersList;
}
public String getProjectAdmin() {
return projectAdmin;
}
public void setProjectAdmin(String projectAdmin) {
this.projectAdmin = projectAdmin;
}
public List<User> getProjectNoUsersList() {
return projectNoUsersList;
}
public void setProjectNoUsersList(List<User> projectNoUsersList) {
this.projectNoUsersList = projectNoUsersList;
}
public List<User> getSelectedUsers() {
return selectedUsers;
}
public void setSelectedUsers(List<User> selectedUsers) {
this.selectedUsers = selectedUsers;
}
}
i'm getting this error:
javax.faces.FacesException: DataModel must implement
org.primefaces.model.SelectableDataModel when selection is enabled.....
just add this attribute rowKey to the datatable tag :
<p:dataTable border="1" value="#{projectAdminisrationMB.projectNoUsersList}"
var="userObj"
rowKey="#{userObj.name}"selection="#{projectAdminisrationMB.selectedUsers}"
selectionMode="multiple" rowIndexVar="rowIndex"
binding="#{table2}">
You can get this error if you try to add a new item to the underlying list and forget to assign a value to that new item's rowKey.
Alternatively to rowKey you can wrap your data in a custom model which really implements org.primefaces.model.SelectableDataModel. This is helpful if
all of your your classes have the same kind of #Id (e.g. a long) and can implement the same interface (e.g. EjbWithId)
you want to add additional functionalities to your data which are not domain specific and don't belong e.g. User.
The interface may be something like this:
public interface EjbWithId
{
public long getId();
public void setId(long id);
}
Then a generic implementation of SelectableDataModel for all your classes can be used:
public class PrimefacesEjbIdDataModel <T extends EjbWithId>
extends ListDataModel<T> implements SelectableDataModel<T>
{
public PrimefacesEjbIdDataModel(List<T> data)
{
super(data);
}
#Override public T getRowData(String rowKey)
{
List<T> list = (List<T>) getWrappedData();
for(T ejb : list)
{
if(ejb.getId()==(new Integer(rowKey))){return ejb;}
}
return null;
}
#Override public Object getRowKey(T item) {return item.getId();}
}
In your #ManagedBean:
private PrimefacesEjbIdDataModel<User> dmUser; //+getter
dmUser = new PrimefacesEjbIdDataModel<User>(administrationProjectFinal.getUserList());
first check whether you've added
rowKey="#{userObj.id}"
then you need to have the data table List set in filteredValue attribute of your data table in xhtml, instead of value.

showing 1-n relations in JSF

I want to place a table on my page. I have two tables in my database for example users and locations. Every location has more than one user. I want to list these locations and show the users who live in these locations.
Los Angeles
John Locke
Dr. Jack
Mr. Eco
Like the below image, could someone do this in JSF?
Thanks.
You can use RichFaces to do such thing:
<h:form>
<rich:dataList var="city" value="#{myBean.allCity}">
<h:outputText value="#{city.name}" ></h:outputText>
<rich:dataList var="user" value="#{city.users}">
<h:outputText value="#{user.name}" ></h:outputText>
</rich:dataList>
</rich:dataList>
</h:form>
Where allCity - list of the City, and every City has list of the user inside.
See http://livedemo.exadel.com/richfaces-demo/richfaces/dataLists.jsf?c=dataList&tab=usage for example.
Backing bean:
myBean:
public class MyBean(){
private ArrayList<City> allCity= new ArrayList<City>();
#PostConstruct
public void init(){
//fill Array list
}
public ArrayList<City> getAllCity() {
return allCity;
}
}
City:
public class City{
private ArrayList<User> users= new ArrayList<User>();
public City( ArrayList<User> users){
this.users = users;
// you can get data from database in myBean, and pass it hear with cinstructor;
}
public ArrayList<User> getUsers() {
return allCity;
}
}
User
public class User{
private String name;
//constructor and others fields;
public String getName(){
return name;
}
}
Only MyBean you register as backing-bean. I show you only base structure of class, how you fill it with data is you choice.

Resources