Ok so i have a data table that is supposed to be an admin page for a book store. I have got everything working on it except i am supposed to have a check box on each row that will switch the outputs to inputs and let you edit a book in the table
i have confirmed through the console that it is running the method and setting the boolean value to true, but it is not re rendering the row to be editable. Any help would be greatly appreciated. I am still very new to JSF
My index page
<h:body>
<h:form>
<h1>Administrator Page</h1>
<br></br>
<br></br>
<h:dataTable value="#{bookDatabase.books}"
rowClasses="evenRow,oddRow"
id="edit"
var="book">
<h:column>
<f:facet name="header">edit</f:facet>
<h:selectBooleanCheckbox value="#{book.editable}"
onclick="submit()"/>
</h:column>
<h:column>
<f:facet name="header">Title</f:facet>
<h:inputText value="#{book.title}"
rendered="#{book.editable}" size="10"/>
<h:outputText value="#{book.title}"
rendered="#{not book.editable}"/>
</h:column>
<h:column>
<f:facet name="header">Author</f:facet>
<h:inputText value="#{book.author}"
rendered="#{book.editable}" size="10"/>
<h:outputText value="#{book.author}"
rendered="#{not book.editable}"/>
</h:column>
<h:column>
<f:facet name="header">Price</f:facet>
<h:outputText id="unitPrice2" value="#{book.price}"
rendered="#{not book.editable}">
<f:convertNumber currencyCode="USD" type="currency" />
</h:outputText>
<h:inputText id="unitPrice" value="#{book.price}"
rendered="#{book.editable}" size="10">
<f:convertNumber currencyCode="USD" type="currency" />
</h:inputText>
</h:column>
<h:column>
<h:commandLink value="Delete"
action="#{bookDatabase.removeBook(book.title)}"/>
</h:column>
</h:dataTable>
<br></br>
Title: <h:inputText id="title" value="#{bookDatabase.title}"/> <br></br>
Author: <h:inputText id="author" value="#{bookDatabase.author}"/> <br></br>
Price: <h:inputText id="price" value="#{bookDatabase.price}"/> <br></br>
<h:commandButton id="submit" value="Submit" action="#{bookDatabase.addBook()}"/>
<br></br>
</h:form>
</h:body>
The book class
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
public class Book implements Serializable {
String title;
String author;
double price;
String orderNumeber;
int quan;
double sub;
double total;
boolean editable;
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
Book() {
title = null;
author = null;
price = 0.0;
orderNumeber = "";
quan = 0;
sub = 0.0;
total = 0.0;
editable = false;
}
public String editableCheck(String title) {
System.out.print(title);
if (this.title.equals(title)) {
if (editable == true) {
editable = false;
} else {
editable = true;
}
}
System.out.print(editable);
return null;
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public int getQuan() {
return quan;
}
public void setQuan(int quan) {
this.quan = quan;
}
public double getSub() {
return sub;
}
public void setSub(double sub) {
this.sub = sub;
}
public String getOrderNumeber() {
return orderNumeber;
}
public void setOrderNumeber(String orderNumeber) {
this.orderNumeber = orderNumeber;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
I dont think my bookDatabase class has any affect on it but here it is just in case
#Named(value = "bookDatabase")
#SessionScoped
public class BookDatabase implements Serializable {
/**
* Creates a new instance of BookDatabase
*/
private List<Book> books;
#Resource(name = "jdbc/database2")
private DataSource ds;
private boolean display;
private boolean edit;
private boolean add;
private boolean remove;
private String title;
private String author;
private String price;
private String bookToRemove;
Book addBook;
#PostConstruct
public void init() {
books = new ArrayList<>();
display = false;
edit = false;
add = false;
remove = false;
addBook = new Book();
title = null;
author = null;
price = null;
bookToRemove= null;
}
public String getBookToRemove() {
return bookToRemove;
}
public void setBookToRemove(String bookToRemove) {
this.bookToRemove = bookToRemove;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public void removeBook() throws SQLException
{
if (ds == null) {
throw new SQLException("ds is null; Can't get data source");
}
Connection conn = ds.getConnection();
if (conn == null) {
throw new SQLException("conn is null; Can't get db connection");
}
try {
System.out.print(bookToRemove);
PreparedStatement ord = conn.prepareStatement("Delete from APP.BOOK where Title = ?");
ord.setString(1, bookToRemove);
ord.execute();
bookToRemove = null;
} finally {
conn.close();
}
}
public void removeBook(String toRemove) throws SQLException
{
bookToRemove = toRemove;
removeBook();
}
public void addBook() throws SQLException {
if (ds == null) {
throw new SQLException("ds is null; Can't get data source");
}
Connection conn = ds.getConnection();
if (conn == null) {
throw new SQLException("conn is null; Can't get db connection");
}
try {
if(author != null && title != null)
{
PreparedStatement ord = conn.prepareStatement("INSERT INTO APP.BOOK (TITLE, AUTHOR, PRICE) "
+ " VALUES (?, ?, ?)");
ord.setString(1, title);
ord.setString(2, author);
ord.setDouble(3, Double.parseDouble(price));
ord.execute();
author = null;
title=null;
price = null;
}
} finally {
conn.close();
}
}
public void renderDisplay() {
display = true;
edit = false;
add = false;
remove = false;
}
public void renderEdit() {
display = false;
edit = true;
add = false;
remove = false;
}
public void renderAdd() {
display = false;
edit = false;
add = true;
remove = false;
}
public void renderRemove() {
display = false;
edit = false;
add = false;
remove = true;
}
public boolean isDisplay() {
return display;
}
public void setDisplay(boolean display) {
this.display = display;
}
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
public boolean isAdd() {
return add;
}
public void setAdd(boolean add) {
this.add = add;
}
public boolean isRemove() {
return remove;
}
public void setRemove(boolean remove) {
this.remove = remove;
}
public List<Book> getBooks() throws SQLException {
books.clear();
if (ds == null) {
throw new SQLException("ds is null; Can't get data source");
}
Connection conn = ds.getConnection();
if (conn == null) {
throw new SQLException("conn is null; Can't get db connection");
}
try {
PreparedStatement ps = conn.prepareStatement(
"select TITLE, AUTHOR, PRICE from BOOK"
);
ResultSet result = ps.executeQuery();
while (result.next()) {
Book b = new Book();
b.setAuthor(result.getString("AUTHOR"));
b.setTitle(result.getString("TITLE"));
b.setPrice(result.getDouble("PRICE"));
books.add(b);
}
} finally {
conn.close();
}
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
public String getSpecificTitle(int number) {
Book currentBook = (Book) books.get(number);
return currentBook.getTitle();
}
public String getSpecificAuthor(int number) {
Book currentBook = (Book) books.get(number);
return currentBook.getAuthor();
}
public double getSpecificPrice(int number) {
Book currentBook = (Book) books.get(number);
return currentBook.getPrice();
}
}
Again thank you so much for any help you may be able to give me
OK folks i have figured out my issue. i was clearing the array of books everytime i called get books in bookDatabase
public List<Book> getBooks() throws SQLException {
books.clear();
I changed this to an if check to see if the array was empty and it now works.
Tiny i also took your advise and moved my logic out of the get method for books. thank you for your help. I am slowly but surly getting better at JSF.
Related
This question already has answers here:
instanceof check in EL expression language
(7 answers)
Closed 6 years ago.
I have two entities, Vehicle and Lorry, lorry have special property maxWeight. These entities have own Table - Vehicle, with parameters idVehicle,licensePlate,amountKM and maxWeight. How i can call this parameter during -
<h:dataTable var="v" value="#{vehicleMB.allVehicle}">
<h:column headerClass="tableHeader">
<f:facet name="header">License plate</f:facet>
#{v.licensePlate}
</h:column>
<h:column headerClass="tableHeader">
<f:facet name="header">Max weight</f:facet>
#{*******maxWeight******}
</h:column>
</h:dataTable>
becouse v.maxWeight is unknown. Method getAllVehicle just selects all vehicles from table. Any tips ?
Lorry class :
#Entity
public class Lorry extends Vehicle {
private long maxWeight;
public long getMaxWeight() {
return maxWeight;
}
public void setMaxWeight(long maxWeight) {
this.maxWeight = maxWeight;
}
}
Vehicle class :
#Entity
public class Vehicle {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long idVehicle;
private String licensePlate;
private int amountKM;
#ManyToOne
Company company;
#OneToMany(mappedBy="vehicle")
List<Path> paths;
public List<Path> getPaths() {
return paths;
}
public void setPaths(List<Path> paths) {
this.paths = paths;
}
public long getIdVehicle() {
return idVehicle;
}
public void setIdVehicle(long idVehicle) {
this.idVehicle = idVehicle;
}
public String getLicensePlate() {
return licensePlate;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (idVehicle ^ (idVehicle >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vehicle other = (Vehicle) obj;
if (idVehicle != other.idVehicle)
return false;
return true;
}
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
public int getAmountKM() {
return amountKM;
}
public void setAmountKM(int amountKM) {
this.amountKM = amountKM;
}
}
<h:outputText value="#{v.maxWeight}" rendered="#{v != null and v.class.simpleName eq 'Lorry'}"/>
This question already has answers here:
Conversion Error setting value for 'null Converter' - Why do I need a Converter in JSF?
(2 answers)
Closed 7 years ago.
I'm getting this conversion error message. I'm trying to get a cliente from the selectOneMenu list, then add a bonus to him.
I implemented the converter and the equals/hashcode methods.
Can you see anything wrong?
My XHTML:
<h:body>
<h:form>
<p:panel id="panel" header="Cadastro de bônus">
<p:panelGrid columns="2">
<p:outputLabel value="Cliente: " />
<p:selectOneMenu value="#{clienteBean.cliente}">
<f:selectItem itemLabel="--Selecione um cliente--" />
<f:selectItems value="#{clienteBean.selectClientes}" />
</p:selectOneMenu>
<p:outputLabel value="Informe o valor da venda:" for="valor_venda" />
<p:inputText id="valor_venda"
value="#{bonusBean.bonus.valor_venda}" />
<h:commandButton value="Próximo" action="#{bonusBean.gravar}" />
</p:panelGrid>
</p:panel>
</h:form>
</h:body>
</ui:define>
My DAO:
public class DAOCliente {
public EntityManager getEntityManager() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("cliente");
EntityManager entityManager = factory.createEntityManager();
return entityManager;
}
public void adiciona (Cliente cliente){
EntityManager entityManager = getEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(cliente);
entityManager.getTransaction().commit();
entityManager.close();
}
public void excluir(Cliente cliente)throws Exception{
EntityManager entityManager = getEntityManager();
try {
entityManager.getTransaction().begin();
cliente = entityManager.merge(cliente);
entityManager.remove(cliente);
entityManager.getTransaction().commit();
} finally {
entityManager.close();
}
}
public Cliente consultar (Long id){
Cliente cliente = new Cliente();
EntityManager entityManager = getEntityManager();
try {
entityManager.getTransaction().begin();
cliente = entityManager.find(Cliente.class, id);
entityManager.getTransaction().commit();
}
catch (Exception e) {
entityManager.getTransaction().rollback();
}
finally {
entityManager.close();
}
return cliente;
}
#SuppressWarnings("unchecked")
public List<Cliente> listarTodosClientes() throws Exception{
EntityManager entityManager = getEntityManager();
List<Cliente> lista = null;
try {
Query query = entityManager.createQuery("SELECT c FROM Cliente c");
lista = query.getResultList();
for (Cliente cliente : lista) {
System.out.println("Nome: " + cliente.getNome());
System.out.println("Fone Residencia: " + cliente.getFone_residencia());
System.out.println("Fone Celular: " + cliente.getFone_celular());
System.out.println("Perfil FB: " + cliente.getPerfil_facebook());
System.out.println("------------------------------------");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
entityManager.close();
}
return lista;
}
}
My converter:
#FacesConverter(forClass = ClienteBean.class)
public class ConverterCliente implements Converter {
#Override
public Object getAsObject(FacesContext ctx, UIComponent component, String value) {
if(value!=null && value.trim().length()>0){
Long id = Long.valueOf(value);
DAOCliente dao = new DAOCliente();
return dao.consultar(id);
}
return null;
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
if(value!=null){
Cliente cliente = (Cliente) value;
return cliente.getId().toString();
}
return null;
}
}
My Managed Bean:
#ManagedBean
public class ClienteBean {
private Cliente cliente;
List<Cliente> clientes;
List<SelectItem> selectClientes;
DAOCliente dao = new DAOCliente();
public List<SelectItem> getSelectClientes() throws Exception {
if(selectClientes==null){
selectClientes = new ArrayList<SelectItem>();
clientes = dao.listarTodosClientes();
if(clientes!=null && !clientes.isEmpty()){
SelectItem item;
for(Cliente lista : clientes){
item = new SelectItem(lista, lista.getNome());
selectClientes.add(item);
}
}
}
return selectClientes;
}
public List<Cliente> getClientes() throws Exception{
if(clientes == null){
clientes = dao.listarTodosClientes();
}
return clientes;
}
public Cliente getCliente() {
return cliente;
}
public void gravar() {
dao.adiciona(cliente);
this.cliente = new Cliente();
}
public void excluir(Cliente cliente) throws Exception{
dao.excluir(cliente);
}
public void setClientes(List<Cliente> clientes) {
this.clientes = clientes;
}
}
My Cliente class:
public class Cliente {
#Id #GeneratedValue
private Long id;
private String nome;
private String fone_residencia;
private String fone_celular;
private String perfil_facebook;
#OneToMany(mappedBy = "cliente", fetch = FetchType.EAGER, targetEntity = Bonus.class, cascade = CascadeType.ALL)
private List<Bonus> bonus;
public List<Bonus> getBonus() {
return bonus;
}
public void setBonus(List<Bonus> bonus) {
this.bonus = bonus;
}
public String getPerfil_facebook() {
return perfil_facebook;
}
public void setPerfil_facebook(String perfil_facebook) {
this.perfil_facebook = perfil_facebook;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getFone_residencia() {
return fone_residencia;
}
public void setFone_residencia(String fone_residencia) {
this.fone_residencia = fone_residencia;
}
public String getFone_celular() {
return fone_celular;
}
public void setFone_celular(String fone_celular) {
this.fone_celular = fone_celular;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bonus == null) ? 0 : bonus.hashCode());
result = prime * result
+ ((fone_celular == null) ? 0 : fone_celular.hashCode());
result = prime * result
+ ((fone_residencia == null) ? 0 : fone_residencia.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result
+ ((perfil_facebook == null) ? 0 : perfil_facebook.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cliente other = (Cliente) obj;
if (bonus == null) {
if (other.bonus != null)
return false;
} else if (!bonus.equals(other.bonus))
return false;
if (fone_celular == null) {
if (other.fone_celular != null)
return false;
} else if (!fone_celular.equals(other.fone_celular))
return false;
if (fone_residencia == null) {
if (other.fone_residencia != null)
return false;
} else if (!fone_residencia.equals(other.fone_residencia))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
if (perfil_facebook == null) {
if (other.perfil_facebook != null)
return false;
} else if (!perfil_facebook.equals(other.perfil_facebook))
return false;
return true;
}
#Override
public String toString() {
return "Cliente [id=" + id + ", nome=" + nome + ", fone_residencia="
+ fone_residencia + ", fone_celular=" + fone_celular
+ ", perfil_facebook=" + perfil_facebook + ", bonus=" + bonus
+ "]";
}
}
You should mention the used converter class in the concerned tag to enable conversion :
<p:selectOneMenu value="#{clienteBean.cliente}" converter="converterCliente">
...
</p:selectOneMenu>
hey I am using the following code to create the number of text fields as the user wants
<h:form>
<p>Number Of News <h:inputText value="#{news.noOfFields}" /></p>
<ui:repeat value="#{news.values}" var="item">
<hr/>
News #{item.no}
<h:inputText value="#{item.news}" /><br/>
</ui:repeat>
<hr/>
<h:commandButton styleClass="btn btn-blue" action="#{news.submit}" value="Save" />
</h:form>
The managed bean news has a class News as
#ManagedBean
#SessionScoped
public class News
{
private String noOfFields;
private List<NewsVO> values;
public News()
{
this.values = new ArrayList<NewsVO>();
}
public String submit() {
for(NewsVO newsVO : this.values)
{
System.out.println(newsVO.getNews());
System.out.println(newsVO.getNo());
}
return null;
// save values in database
}
public String getNoOfFields() {
return noOfFields;
}
public List<NewsVO> getValues() {
return values;
}
public void setValues(List<NewsVO> values) {
this.values = values;
}
public void setNoOfFields(String noOfFields) {
this.values = new ArrayList<NewsVO>();
try {
for(int i=0;i<Integer.valueOf(noOfFields);i++)
{
NewsVO newsVO = new NewsVO();
newsVO.setNo(i+1);
this.values.add(newsVO);
}
this.noOfFields = noOfFields;
}
catch(NumberFormatException ex) {
/*values = new String[1];*/
noOfFields = "1";
}
}
}
The NewsVO is just a javaBean class as follows
public class NewsVO
{
public int no;
public String news;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getNews() {
return news;
}
public void setNews(String news) {
this.news = news;
}
}
The problem is the values inside the input Text doesn't get reflected on pressing the save button. It gives me null, even though, I have written something inside all the textfields.
<h:inputText value="#{item.news}" />
Everytime you push the submit button, all setters in the bean are called (including setNoOfFields()). In this setter you are resetting your list, that's why you loose your values. Since you only need to modify your list if there is a size change, here is a simple way doing it :
#ManagedBean
#SessionScoped
public class News
{
private int noOfFields;
private List<NewsVO> values;
public News()
{
this.values = new ArrayList<NewsVO>();
}
public String submit()
{
for(NewsVO newsVO : this.values)
{
System.out.println(newsVO.getNews());
System.out.println(newsVO.getNo());
}
return null;
// save values in database
}
public int getNoOfFields()
{
return noOfFields;
}
public List<NewsVO> getValues()
{
return values;
}
public void setValues(List<NewsVO> values)
{
this.values = values;
}
public void setNoOfFields(int noOfFields)
{
if(noOfFields < this.noOfFields)
{
for(int i = this.noOfFields - 1;i >= noOfFields;i--)
{
getValues().remove(i);
}
}
else if(noOfFields > this.noOfFields)
{
for(int i = this.noOfFields;i < noOfFields;i++)
{
NewsVO newsVO = new NewsVO();
newsVO.setNo(i+1);
getValues().add(newsVO);
}
}
}
}
Note : I've also changed your noOfFields getter/setter for simple int, JSF will do the conversion for you.
my jsf page
<h:form>
<h:dataTable id="btable" value="#{ballController.items}" var="item">
<h:column>
<h:outputText value="#{item.id}"/>
</h:column>
<h:column>
<h:outputText value="#{item.bname}"/>
</h:column>
</h:dataTable>
<h:commandButton action="#{ballCOntroller.items}" value="test">
<f:ajax execute="#form" render="btable" />
</h:commandButton>
</h:form>
in my controller, this method is called by ballController.items
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
but upon clicking the button itl give me an error saying:
serverError: classjavax.faces.el.MethodNotFoundException
/app/ball/index.xhtml #40,101 action="#{ballController.items}": Method
not found: ballController#a7150b6.items()
my goal is to reload the dataTable on clicking the command button without refreshing the entire page.
*Edited
my whole bean code
#ManagedBean(name = "ballController")
#ViewScoped
public class ballController implements Serializable {
private ball current;
private DataModel items = null;
#EJB
private ballFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public ballController() {
}
public ball getSelected() {
if (current == null) {
current = new ball();
selectedItemIndex = -1;
}
return current;
}
private ballFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (ball) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new ball();
selectedItemIndex = -1;
return "index";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ballCreated"));
return prepareCreate();
// return null;
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (ball) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ballUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (ball) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ballDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
#FacesConverter(forClass = ball.class)
public static class ballControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
ballController controller = (ballController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "ballController");
return controller.ejbFacade.find(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof ball) {
ball o = (ball) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ball.class.getName());
}
}
}
}
To reload the table , you just need to use <f:ajax render="btable" />
<h:commandButton value="test">
<f:ajax render="btable" />
</h:commandButton>
But to to do some action , like adding some data to table you need to point the button to a a proper method
<h:commandButton value="test" action="#{ballController.addItem}"">
<f:ajax render="btable" />
</h:commandButton>
public void addItem() {
if (items == null) {
items = getPagination().createPageDataModel();
}
items.getWrappedData().add(/*something like new MyObject("one","two")*/);
}
serverError: classjavax.faces.el.MethodNotFoundException /app/ball/index.xhtml #40,101 action="#{ballController.items}": Method not found: ballController#a7150b6.items()
Is occurring because you are trying to access getItems in an incorrect way.
Update your bean code as:
public DataModel items() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
or else change your facelet action EL expression as action="#{ballCOntroller.getItems}".
EDIT
You can update your List as:
public class DataTableBean implements Serializable {
List<String> dataModelList = new ArrayList<DataModel>();
public List<DataModel> getDataModelList() {
return dataTableList;
}
public void setDataModelList(List<String> dataModelList) {
this.dataTableList = dataTableList;
}
public void addItems(){
List<DataModel> tempList = getPagination().createPageDataModel(); // Returns a list of type `List<DataModel>`.
dataModelList.addAll(tempList);
}
}
Used a simple InnoDB MySQL database (many to many relationship between WRITER and FORUM, and a join table named writer_forum) in Netbeans 7.1 and created a Java EE 6 web application running under Glassfish 3.1 Open Source Edition. No Other frameworks are being used except JSF 2.0
Generated Entities from Database (using EclipseLink (JPA 2.0) and everything seems fine, the code in the entities is correct as far as I can tell.
Generated JSF pages from Entities (the IDE generates EJB Session beans, Managed Beans and JSF pages using facelets .xhtml).
ALl relationships are supported except MANY TO MANY.
Does anyone had the same experience and managed to enable Many to Many relationship support?
package entities;
#Entity
#Table(name = "writer")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Writer.findAll", query = "SELECT w FROM Writer w"),
#NamedQuery(name = "Writer.findByWriterid", query = "SELECT w FROM Writer w WHERE w.writerid = :writerid"),
#NamedQuery(name = "Writer.findByName", query = "SELECT w FROM Writer w WHERE w.name = :name"),
#NamedQuery(name = "Writer.findBySurname", query = "SELECT w FROM Writer w WHERE w.surname = :surname"),
#NamedQuery(name = "Writer.findByField", query = "SELECT w FROM Writer w WHERE w.field = :field")})
public class Writer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "writerid")
private Integer writerid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "surname")
private String surname;
#Size(max = 45)
#Column(name = "field")
private String field;
#ManyToMany(mappedBy = "writerCollection")
private Collection<Forum> forumCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "writer")
private Collection<Book> bookCollection;
public Writer() {
}
public Writer(Integer writerid) {
this.writerid = writerid;
}
public Writer(Integer writerid, String name, String surname) {
this.writerid = writerid;
this.name = name;
this.surname = surname;
}
public Integer getWriterid() {
return writerid;
}
public void setWriterid(Integer writerid) {
this.writerid = writerid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
#XmlTransient
public Collection<Forum> getForumCollection() {
return forumCollection;
}
public void setForumCollection(Collection<Forum> forumCollection) {
this.forumCollection = forumCollection;
}
#XmlTransient
public Collection<Book> getBookCollection() {
return bookCollection;
}
public void setBookCollection(Collection<Book> bookCollection) {
this.bookCollection = bookCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (writerid != null ? writerid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Writer)) {
return false;
}
Writer other = (Writer) object;
if ((this.writerid == null && other.writerid != null) || (this.writerid != null && !this.writerid.equals(other.writerid))) {
return false;
}
return true;
}
#Override
public String toString() {
return name + " | " + writerid;
}
}
-------- FORUM JPA entity
#Entity
#Table(name = "forum")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Forum.findAll", query = "SELECT f FROM Forum f"),
#NamedQuery(name = "Forum.findByForumid", query = "SELECT f FROM Forum f WHERE f.forumid = :forumid"),
#NamedQuery(name = "Forum.findByLabel", query = "SELECT f FROM Forum f WHERE f.label = :label")})
public class Forum implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "forumid")
private Integer forumid;
#Size(max = 45)
#Column(name = "label")
private String label;
#JoinTable(name = "forum_writer", joinColumns = {
#JoinColumn(name = "forum_forumid", referencedColumnName = "forumid")}, inverseJoinColumns = {
#JoinColumn(name = "writer_writerid", referencedColumnName = "writerid")})
#ManyToMany
private Collection<Writer> writerCollection;
public Forum() {
}
public Forum(Integer forumid) {
this.forumid = forumid;
}
public Integer getForumid() {
return forumid;
}
public void setForumid(Integer forumid) {
this.forumid = forumid;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
#XmlTransient
public Collection<Writer> getWriterCollection() {
return writerCollection;
}
public void setWriterCollection(Collection<Writer> writerCollection) {
this.writerCollection = writerCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (forumid != null ? forumid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Forum)) {
return false;
}
Forum other = (Forum) object;
if ((this.forumid == null && other.forumid != null) || (this.forumid != null && !this.forumid.equals(other.forumid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.Forum[ forumid=" + forumid + " ]";
}
}
Asbtract Facade
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
Forum Facade
#Stateless
public class ForumFacade extends AbstractFacade<Forum> {
#PersistenceContext(unitName = "writerPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public ForumFacade() {
super(Forum.class);
}
}
------------- Managed Bean
#ManagedBean(name = "writerController")
#SessionScoped
public class WriterController implements Serializable {
private Writer current;
private DataModel items = null;
#EJB
private session.WriterFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public WriterController() {
}
public Writer getSelected() {
if (current == null) {
current = new Writer();
selectedItemIndex = -1;
}
return current;
}
private WriterFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Writer) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Writer();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("WriterCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Writer) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("WriterUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Writer) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("WriterDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
#FacesConverter(forClass = Writer.class)
public static class WriterControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
WriterController controller = (WriterController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "writerController");
return controller.ejbFacade.find(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Writer) {
Writer o = (Writer) object;
return getStringKey(o.getWriterid());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + WriterController.class.getName());
}
}
}
}
---------- XTMLCreate PAGE for WRITER----
**
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<ui:composition template="/template.xhtml">
<ui:define name="title">
<h:outputText value="#{bundle.CreateWriterTitle}"></h:outputText>
</ui:define>
<ui:define name="body">
<h:panelGroup id="messagePanel" layout="block">
<h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>
</h:panelGroup>
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="#{bundle.CreateWriterLabel_writerid}" for="writerid" />
<h:inputText id="writerid" value="#{writerController.selected.writerid}" title="#{bundle.CreateWriterTitle_writerid}" required="true" requiredMessage="#{bundle.CreateWriterRequiredMessage_writerid}"/>
<h:outputLabel value="#{bundle.CreateWriterLabel_name}" for="name" />
<h:inputText id="name" value="#{writerController.selected.name}" title="#{bundle.CreateWriterTitle_name}" required="true" requiredMessage="#{bundle.CreateWriterRequiredMessage_name}"/>
<h:outputLabel value="#{bundle.CreateWriterLabel_surname}" for="surname" />
<h:inputText id="surname" value="#{writerController.selected.surname}" title="#{bundle.CreateWriterTitle_surname}" required="true" requiredMessage="#{bundle.CreateWriterRequiredMessage_surname}"/>
<h:outputLabel value="#{bundle.CreateWriterLabel_field}" for="field" />
<h:inputText id="field" value="#{writerController.selected.field}" title="#{bundle.CreateWriterTitle_field}" />
</h:panelGrid>
<br />
<h:commandLink action="#{writerController.create}" value="#{bundle.CreateWriterSaveLink}" />
<br />
<br />
<h:commandLink action="#{writerController.prepareList}" value="#{bundle.CreateWriterShowAllLink}" immediate="true"/>
<br />
<br />
<h:commandLink value="#{bundle.CreateWriterIndexLink}" action="/index" immediate="true" />
</h:form>
</ui:define>
</ui:composition>
</html>
**
I am not 100% sure but I think, you may not retrieving any results beacuse of #XMLTransiet annotation above the Serie.class method;
#XmlTransient
public Collection<Writer> getWriterCollection() {
return writerCollection;
}
I would also like to review these documents https://docs.oracle.com/javaee/6/api/javax/xml/bind/annotation/XmlTransient.html