one to one mapping Entity class from dataBase using netbeans jpa - jsf

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;
}
}

Related

jsf static list won't show up in datatable

I'm trying to get a list to show in datatable from managed bean to JSF page but it doesn't work.
it's telling me " not records found " .
JSF managed bean :
#ManagedBean
#RequestScoped
public class TestController {
private List<Rhnom> list = new ArrayList<Rhnom>();
#SuppressWarnings("serial")
private List<String> list2 = new ArrayList<String>() {{
add("s1");
add("s2");
add("s3");
}};
//getters and setters
JSF page :
<p:dataTable value="#{tesController.list2}" var="type">
<p:column headerText="Lib">
<h:outputText value="#{type}">
</h:outputText>
</p:column>
</p:dataTable>
I consider that you have problems with the implementation
Link
https://www.primefaces.org/showcase/ui/data/datatable/basic.xhtml
Example
<p:dataTable var="car" value="#{dtBasicView.cars}">
<p:column headerText="Id">
<h:outputText value="#{car.id}" />
</p:column>
<p:column headerText="Year">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Brand">
<h:outputText value="#{car.brand}" />
</p:column>
<p:column headerText="Color">
<h:outputText value="#{car.color}" />
</p:column>
</p:dataTable>
Managebean
#Named("dtBasicView")
#ViewScoped
public class BasicView implements Serializable {
private List<Car> cars;
#Inject
private CarService service;
#PostConstruct
public void init() {
cars = service.createCars(10);
}
public List<Car> getCars() {
return cars;
}
public void setService(CarService service) {
this.service = service;
}
}
Java Class
#Named
#ApplicationScoped
public class CarService {
private final static String[] colors;
private final static String[] brands;
static {
colors = new String[10];
colors[0] = "Black";
colors[1] = "White";
colors[2] = "Green";
colors[3] = "Red";
colors[4] = "Blue";
colors[5] = "Orange";
colors[6] = "Silver";
colors[7] = "Yellow";
colors[8] = "Brown";
colors[9] = "Maroon";
brands = new String[10];
brands[0] = "BMW";
brands[1] = "Mercedes";
brands[2] = "Volvo";
brands[3] = "Audi";
brands[4] = "Renault";
brands[5] = "Fiat";
brands[6] = "Volkswagen";
brands[7] = "Honda";
brands[8] = "Jaguar";
brands[9] = "Ford";
}
public List<Car> createCars(int size) {
List<Car> list = new ArrayList<Car>();
for(int i = 0 ; i < size ; i++) {
list.add(new Car(getRandomId(), getRandomBrand(), getRandomYear(), getRandomColor(), getRandomPrice(), getRandomSoldState()));
}
return list;
}
private String getRandomId() {
return UUID.randomUUID().toString().substring(0, 8);
}
private int getRandomYear() {
return (int) (Math.random() * 50 + 1960);
}
private String getRandomColor() {
return colors[(int) (Math.random() * 10)];
}
private String getRandomBrand() {
return brands[(int) (Math.random() * 10)];
}
private int getRandomPrice() {
return (int) (Math.random() * 100000);
}
private boolean getRandomSoldState() {
return (Math.random() > 0.5) ? true: false;
}
public List<String> getColors() {
return Arrays.asList(colors);
}
public List<String> getBrands() {
return Arrays.asList(brands);
}
}

Display Data from multiple tables

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>
...

Primefaces datatable with delete button not working

I'm trying to delete one cell with a <p:commandButton> and after i click i want to update my table. But all what happens is, that i got this Exception.
javax.persistence.EntityNotFoundException: Unable to find de.test.Datei with id 5
But in my Database i can see the facts in each table. Also when i click the button, the dates will be delete correctly. But my table doesn't update, so the cell isn't disappeared. And when i click twice, i got the above error message.
Datei.class
#Entity
public class Datei implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "DATA_ID_GENERATOR", sequenceName = "SEQ_DATA", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "DATA_ID_GENERATOR")
private long id;
private String name;
private long groesse;
#Temporal(TemporalType.TIMESTAMP)
private Date datum;
#Basic(fetch = FetchType.LAZY)
#Lob
private byte[] datei;
#ManyToOne
private Benutzer benutzer;
public Benutzer getBenutzer() {
return benutzer;
}
public void setBenutzer(Benutzer benutzer) {
this.benutzer = benutzer;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getGroesse() {
return groesse;
}
public void setGroesse(long groesse) {
this.groesse = groesse;
}
public byte[] getDatei() {
return datei;
}
public void setDatei(byte[] datei) {
this.datei = datei;
}
public Datei() {
// TODO Auto-generated constructor stub
}
public Date getDatum() {
return datum;
}
public void setDatum(Date datum) {
this.datum = datum;
}
#Override
public String toString() {
return "Datei [id=" + id + ", name=" + name + ", groesse=" + groesse
+ ", datum=" + datum + ", datei=" + Arrays.toString(datei)
+ "]";
}
}
Benutzer.class
#Entity
public class Benutzer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "CUSTOMER_ID_GENERATOR", sequenceName = "SEQ_CUSTOMER", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CUSTOMER_ID_GENERATOR")
private long id;
private String name;
private String email;
private long kundennummer;
#OneToMany(mappedBy = "benutzer", orphanRemoval = true)
private List<Datei> datei;
#Override
public String toString() {
return "Benutzer [id=" + id + ", name=" + name + ", email=" + email
+ ", kundennummer=" + kundennummer + ", datei=" + datei + "]";
}
public List<Datei> getDatei() {
return datei;
}
public void setDatei(List<Datei> datei) {
this.datei = datei;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getKundennummer() {
return kundennummer;
}
public void setKundennummer(long kundennummer) {
this.kundennummer = kundennummer;
}
public Benutzer() {
// TODO Auto-generated constructor stub
}
}
My DateiDAO.class
[...]
public void loeschen(Datei datei, Benutzer benutzer) {
EntityManager em = emf.createEntityManager();
EntityTransaction tr = em.getTransaction();
tr.begin();
benutzer = em.merge(benutzer);
datei = em.merge(datei);
tr.commit();
benutzer.getDatei().remove(datei);
tr.begin();
em.merge(benutzer);
em.remove(em.merge(datei));
tr.commit();
}
So the only problem is, that my table dosen't update.
If i use richfaces, it works fine.
main.xhtml
<h:form id="myForm">
<p:dataTable id="dateien" var="data"
value="#{mainController.ben.datei}" rowKey="#{data.id}"
selectionMode="single" rows="5" paginator="true" rowsPerPageTemplate="5,10,15" paginatorPosition="bottom"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}">
<f:facet name="header">
<h:outputText value="Uploaded"/>
</f:facet>
<p:column headerText="Id">
<h:outputText value="#{data.id}" />
</p:column>
<p:column headerText="Name">
<h:outputText value="#{data.name}" />
</p:column>
<p:column headerText="Datum">
<h:outputText value="#{data.datum}" />
</p:column>
<p:column headerText="Delete">
<p:commandButton update="myForm"
actionListener="#{mainController.loeschen(data)}"
icon="ui-icon-trash" />
</p:column>
</p:dataTable>
</h:form>
Miss it in your process:
Delete this item from your mainController.ben.datei list after you delete item from database, and update your dataTable like Ouerghi Yassine told.
or
Get load again your data list from database on loeschen method after you delete item, its more security if you do this system and wish no have a concurrence problem.
So, you provide to your dataTable one list binding with your bean, in your case the datei list, so even if you delete item from database, this item cant be this list too.
I'm sorry for my english.
Add update="dateien" to your commandButton
<p:commandButton update="myForm"
actionListener="#{mainController.loeschen(data)}"
icon="ui-icon-trash"
update="dateien"/>

primefaces not show dataTable values with lazyModel

I'm starting with primefaces and I try use LazyModel in p:dataTable.
I already implemented the LazyModel, bean and jsf. The call's to bean and model occur's correctly and my bean return a list with elements, but my jsf show nothing.
Please, somebody know whats happen?
Bellow is my code:
JSF:
<ui:composition template="./newTemplate.xhtml">
<ui:define name="content">
content
<h:form>
<p:panel id="formFiltro">
<p:messages id="messages"/>
<h:panelGrid>
<h:outputLabel for="fieldConta" value="Número da Conta:"/>
<p:inputText id="fieldConta" value="#{log.nrConta}" label="Número da Conta">
<f:convertNumber integerOnly="true" type="number"/>
</p:inputText>
<!--<p:message for="fieldConta" />-->
<h:outputLabel for="fieldAgencia" value="Código da Agência:"/>
<p:inputText id="fieldAgencia" value="#{log.nrAgencia}" label="Código da Agência">
<f:convertNumber integerOnly="true" type="number"/>
</p:inputText>
<!--<p:message for="fieldAgencia" />-->
<center>
<p:commandButton ajax="false" value="Pesquisar" action="#{log.search}" />
</center>
</h:panelGrid>
</p:panel>
<p:dataTable var="l" value="#{log.lazyLogModel}" paginator="true" rows="5"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15" id="logTable" lazy="true">
<p:column headerText="ID">
<h:outputText value="#{l.logId}" />
</p:column>
<p:column headerText="Agência">
<h:outputText value="#{l.logAgencia}" />
</p:column>
<p:column headerText="Conta">
<h:outputText value="#{l.logConta}" />
</p:column>
<p:column headerText="SO">
<h:outputText value="#{l.logSo}" />
</p:column>
<p:column headerText="Plugin">
<h:outputText value="#{l.logVersaoPlugin}" />
</p:column>
<p:column headerText="Tam F10">
<h:outputText value="#{l.logTamF10}" />
</p:column>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
My bean:
#ManagedBean(name="log")
#RequestScoped
public class consultaJsf implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of consultaJsf
*/
private List<TbLogLog> listaLog;
private LazyLogModel lazyLogModel;
private int nrConta;
private int nrAgencia;
public consultaJsf() {
try{
//this.listaLog = new ConsultarDados().getListLogAll();
}catch(Exception e){
e.printStackTrace();
}
}
#PostConstruct
public void init()
{
this.lazyLogModel = new LazyLogModel();
}
public List<TbLogLog> getListaLog()
{
return listaLog;
}
public int getNrConta()
{
return nrConta;
}
public void setNrConta(int nrConta)
{
this.nrConta = nrConta;
}
public int getNrAgencia()
{
return nrAgencia;
}
public void setNrAgencia(int nrAgencia)
{
this.nrAgencia = nrAgencia;
}
public LazyLogModel getLazyLogModel()
{
return this.lazyLogModel;
}
public String search() throws Exception
{
if(nrConta != 0)
this.listaLog = new ConsultarDados().getListLogByConta(nrConta);
else if(nrAgencia != 0)
this.listaLog = new ConsultarDados().getListLogByAgencia(nrAgencia);
return null;
}
}
My LazyModel:
public class LazyLogModel extends LazyDataModel<TbLogLog> {
private String nrConta;
private String cdAgencia;
#Override
public List<TbLogLog> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
List<TbLogLog> listaLog = null;
try{
listaLog = new ConsultarDados().getListLogAll(first, pageSize);
}catch(Exception e){
return null;
}
return listaLog;
}
/**
* #return the nrConta
*/
public String getNrConta() {
return nrConta;
}
/**
* #param nrConta the nrConta to set
*/
public void setNrConta(String nrConta) {
this.nrConta = nrConta;
}
/**
* #return the cdAgencia
*/
public String getCdAgencia() {
return cdAgencia;
}
/**
* #param cdAgencia the cdAgencia to set
*/
public void setCdAgencia(String cdAgencia) {
this.cdAgencia = cdAgencia;
}
}
Consult Method called by LazyModel:
private List<TbLogLog> getListLog(String hql, int firstResult, int sizePage) throws Exception {
List resultList = null;
try {
Session session = HubernateUtil.getSessionFactory().openSession();
if ((hql == null) || (hql.trim().length() == 0)) {
hql = QUERY_PESQUISAR_TODOS;
}
Query q = session.createQuery(hql);
if(firstResult > 0 )
q.setFirstResult(firstResult);
if(sizePage > 0)
q.setMaxResults(sizePage);
resultList = q.list();
} catch (HibernateException he) {
he.printStackTrace();
}
return resultList;
}
Everything work's fine, but my jsf don't show any result.
Thanks in advance.
Remove the init() in consultaJsf Class and update the getLazyLogModel() as follows
#ManagedBean(name="log")
#RequestScoped
public class consultaJsf implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of consultaJsf
*/
private List<TbLogLog> listaLog;
private LazyLogModel<TbLogLog> lazyLogModel;
private int nrConta;
private int nrAgencia;
public consultaJsf() {
try{
//this.listaLog = new ConsultarDados().getListLogAll();
}catch(Exception e){
e.printStackTrace();
}
}
public List<TbLogLog> getListaLog()
{
return listaLog;
}
public int getNrConta()
{
return nrConta;
}
public void setNrConta(int nrConta)
{
this.nrConta = nrConta;
}
public int getNrAgencia()
{
return nrAgencia;
}
public void setNrAgencia(int nrAgencia)
{
this.nrAgencia = nrAgencia;
}
public LazyLogModel<TbLogLog> getLazyLogModel()
{
if (lazyLogModel== null) {
lazyLogModel= new LazyDataModel<TbLogLog>() {
#Override
public List<TbLogLog> load(int first, int pageSize, String sortField,
SortOrder sortOrder, Map<String, String> filters) {
List<TbLogLog> listaLog = null;
try{
listaLog = new ConsultarDados().getListLogAll(first, pageSize);
}catch(Exception e){
return null;
}
return listaLog;
}
};
}
return listaLog;
}
public String search() throws Exception
{
if(nrConta != 0)
this.listaLog = new ConsultarDados().getListLogByConta(nrConta);
else if(nrAgencia != 0)
this.listaLog = new ConsultarDados().getListLogByAgencia(nrAgencia);
return null;
}
}

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.

Resources