I am trying to create a new order by selecting a customer name from a SelectOneMenu. I am getting a Conversion error setting value for 'null Converter'.
Order.java
#Entity
#Table(name = "order")
public class Order
{
#Id
#Column(name = "ORDER_ID", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private long orderId;
#JoinColumn(name = "PRODUCT_ID", referencedColumnName = "PRODUCT_ID")
private Product product;
#Column(name = "QUANTITY")
private int quantity;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "ORDER_DATE")
private Date orderDate;
#ManyToOne(optional = false)
#JoinColumn(name = "CUSTOMER_ID", referencedColumnName = "CUSTOMER_ID")
private Customer customer;
// Getters & Setters
}
newOrder.xhtml
<h:outputLabel value="Customer: "/>
<h:selectOneMenu id="customer" value="#{solController.order.customer}" >
<f:selectItem itemLabel="" itemDisabled="true"/>
<f:selectItems value="#{solController.customerList}" var="customer" id="customerID" itemLabel="#{customer.customerName}" itemValue="#{customer.customerId}" />
</h:selectOneMenu>
SolController.java
#ManagedBean(name = "solController")
#SessionScoped
public class SolController implements Serializable
{
#EJB
private SolEJB solEJB;
private Order order = new Order();
private List<Order> orderList = new ArrayList<Order>();
public String doCreateOrder()
{
order = solEJB.createOrder(order);
orderList = solEJB.findOrders();
return "listOrders.xhtml";
}
// Getters & Setters
}
SolEJB.java
#Stateless
public class SolEJB
{
#PersistenceContext(unitName = "myPU")
private EntityManager em;
public Order createOrder(Order order)
{
em.persist(order);
return order;
}
}
Related
I would like to create a JSF application
Where a user must provide their age. This will default to 18 and be editable (If the user wants to provide a different value).
How to achieve this functionality?
The input value provided by the user or the default value ie which is 18 would be saved in the Database
<h:form>
<p:panel id="panel" header="New User">
<h:panelGrid columns="3" cellpadding="5">
<p:outputLabel for="age" value="Age:" />
<p:inputText id="age" value="#{managedBean.entityBean.age}" required="true" label="Age">
</p:inputText>
</h:panelGrid>
<p:commandButton value="Save" update="panel" action="#{managedBean.save}" />
</p:panel>
</h:form>
Entity.java
public class Entity implements Serializable {
#Column(name = "AGE")
private Integer age;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
managedBean.java
#ManagedBean(name = "managedBeanJava")
#ViewScoped
public class managedBeanJava implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(managedBeanJava.class);
private Entity entityBean;
public Entity getEntityBean() {
return entityBean;
}
public void setEntityBean(Entity entityBean) {
this.entityBean = entityBean;
}
private Integer age = 50;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#PostConstruct
public void init() {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, String> params = externalContext.getRequestParameterMap();
}
public void save(AjaxBehaviorEvent event) {
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
entityBean.setAge(this.entityBean.getAge());
}
}
You could define default value of <h:inputText> in your managed bean directly.
private Integer age = 18;
I want to show the list of the plot from the database. I have created plot.java in package bookingSessionBean and viewPlot.java in package viewBean, but it doesn't work.
index.xhtml code:
<h:body>
<h1><h:outputText value="Selected Plot" /></h1>
<h:form>
<f:view>
<h:dataTable value="#{viewPlot.plots}" var="item">
<h:column>
<h:outputText value="#{item.plotno}" />
</h:column>
</h:dataTable>
</f:view>
</h:form>
</h:body>
viewPlot.java code
#ManagedBean
#Named(value = "viewPlot")
#SessionScoped
public class viewPlot implements Serializable {
#PersistenceContext(unitName = "2day4uPU")
private EntityManager em;
public viewPlot() {
}
public List<Plot> getPlots()
{
return em.createNamedQuery("Plot.findAll").getResultList();
}
}
Plot.java code
#Entity
#Table(name = "PLOT")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Plot.findAll", query = "SELECT p FROM Plot p"),
#NamedQuery(name = "Plot.findByPlotno", query = "SELECT p FROM Plot p WHERE p.plotno = :plotno"),
#NamedQuery(name = "Plot.findByStartdate", query = "SELECT p FROM Plot p WHERE p.startdate = :startdate"),
#NamedQuery(name = "Plot.findByEnddate", query = "SELECT p FROM Plot p WHERE p.enddate = :enddate"),
#NamedQuery(name = "Plot.findByAvailableplot", query = "SELECT p FROM Plot p WHERE p.availableplot = :availableplot")})
public class Plot implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "PLOTNO")
private Integer plotno;
#Basic(optional = false)
#NotNull
#Column(name = "STARTDATE")
#Temporal(TemporalType.DATE)
private Date startdate;
#Basic(optional = false)
#NotNull
#Column(name = "ENDDATE")
#Temporal(TemporalType.DATE)
private Date enddate;
#Column(name = "AVAILABLEPLOT")
private Integer availableplot;
#JoinColumn(name = "ACCOMNO", referencedColumnName = "ACCOMNO")
#ManyToOne(optional = false)
private Accomodation accomno;
#JoinColumn(name = "SITENO", referencedColumnName = "SITENO")
#ManyToOne(optional = false)
private Site siteno;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "plotno")
private Collection<Booking> bookingCollection;
public Plot() {
}
public Plot(Integer plotno) {
this.plotno = plotno;
}
public Plot(Integer plotno, Date startdate, Date enddate) {
this.plotno = plotno;
this.startdate = startdate;
this.enddate = enddate;
}
public Integer getPlotno() {
return plotno;
}
public void setPlotno(Integer plotno) {
this.plotno = plotno;
}
public Date getStartdate() {
return startdate;
}
public void setStartdate(Date startdate) {
this.startdate = startdate;
}
public Date getEnddate() {
return enddate;
}
public void setEnddate(Date enddate) {
this.enddate = enddate;
}
public Integer getAvailableplot() {
return availableplot;
}
public void setAvailableplot(Integer availableplot) {
this.availableplot = availableplot;
}
public Accomodation getAccomno() {
return accomno;
}
public void setAccomno(Accomodation accomno) {
this.accomno = accomno;
}
public Site getSiteno() {
return siteno;
}
public void setSiteno(Site siteno) {
this.siteno = siteno;
}
#XmlTransient
public Collection<Booking> getBookingCollection() {
return bookingCollection;
}
public void setBookingCollection(Collection<Booking> bookingCollection) {
this.bookingCollection = bookingCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (plotno != null ? plotno.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 Plot)) {
return false;
}
Plot other = (Plot) object;
if ((this.plotno == null && other.plotno != null) || (this.plotno != null && !this.plotno.equals(other.plotno))) {
return false;
}
return true;
}
#Override
public String toString() {
return "bookingSessionBean.Plot[ plotno=" + plotno + " ]";
}
}
[ how can I solve this error? ]
I have the following bean:
import java.util.List;
import javax.faces.bean.RequestScoped;
import javax.annotations.ManagedBean;
import javax.persistence.EntityManager;
import listener.EMF;
import model.CustomerOrder;
#MangedBean
#RequestScoped
public class OrderBean {
private List<CustomerOrder> orderList;
/**
* Creates a new instance of OrderBean
*/
public OrderBean() {
EntityManager em = EMF.createEntityManager();
this.orderList = em.createNamedQuery("CustomerOrder.findAll").getResultList();
System.out.println("=== Orderlist ===");
for (CustomerOrder order : orderList) {
System.out.println(order.getNumber());
}
em.close();
}
public List<CustomerOrder> getOrderList() {
System.out.println("=== In getOrderList ===");
return orderList;
}
public void setOrderList(List<CustomerOrder> orderList) {
this.orderList = orderList;
}
}
The CustomerOrder class is a JPA class:
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.*;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import listener.EMF;
import regex.AttachmentAnalyzer;
#Entity
#Table(name = "customerorder")
#NamedQueries({
#NamedQuery(name = "CustomerOrder.findAll", query = "SELECT c FROM CustomerOrder c"),
#NamedQuery(name = "CustomerOrder.findById", query = "SELECT c FROM CustomerOrder c WHERE c.id = :id"),
#NamedQuery(name = "CustomerOrder.findByNumber", query = "SELECT c FROM CustomerOrder c WHERE c.number = :number"),
#NamedQuery(name = "CustomerOrder.findByCalculationparameter", query = "SELECT c FROM CustomerOrder c WHERE c.calculationparameter = :calculationparameter"),
#NamedQuery(name = "CustomerOrder.findByActive", query = "SELECT c FROM CustomerOrder c WHERE c.active = :active"),
#NamedQuery(name = "CustomerOrder.findByLastupdate", query = "SELECT c FROM CustomerOrder c WHERE c.lastupdate = :lastupdate")})
public class CustomerOrder implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Size(max = 255)
#Column(name = "number")
private String number;
#Column(name = "calculationparameter")
private BigDecimal calculationparameter;
#Column(name = "active")
private Short active;
#Basic(optional = false)
#NotNull
#Column(name = "lastupdate")
#Temporal(TemporalType.TIMESTAMP)
private Date lastupdate;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "customerorderId")
private List<Orderline> orderlineList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "customerorderId")
private List<Attachment> attachmentList;
#JoinColumn(name = "lastupdateby", referencedColumnName = "id")
#ManyToOne(optional = false)
private User lastupdateby;
#JoinColumn(name = "customer_id", referencedColumnName = "id")
#ManyToOne
private Customer customerId;
#Transient
private boolean validOrder;
public CustomerOrder() {
}
public CustomerOrder(Email email) {
this.attachmentList = email.getAttachments();
EntityManager em = EMF.createEntityManager();
List<Customer> customers = em.createNamedQuery("Customer.findAll").getResultList();
User systemUser = (User) em.createNamedQuery("User.findByName").setParameter("name", "system").getSingleResult();
em.close();
for (Customer customer : customers) {
String fromAddressFilter = customer.getEmailaddressfilter();
String subjectFilter = customer.getEmailsubjectfilter();
String subject = email.getSubject();
String content = email.getContent();
if (isMatch(email.getSubject(), subjectFilter)
&& isMatch(email.getFromAddress(), fromAddressFilter)) {
this.validOrder = true;
this.active = 1;
AttachmentAnalyzer analyzer = new AttachmentAnalyzer(customer, subject, content, attachmentList);
this.number = analyzer.getNumber();
this.calculationparameter = analyzer.getCalculationParameter();
this.orderlineList = analyzer.getOrderlineList();
this.customerId = customer;
this.lastupdateby = systemUser;
for (Attachment a : attachmentList) {
a.setCustomerorderId(this);
}
for (Orderline o : orderlineList) {
o.setCustomerorderId(this);
o.setLastupdateby(systemUser);
}
} else {
this.validOrder = false;
}
}
}
private boolean isMatch(String string, String filter) {
Pattern pattern;
pattern = Pattern.compile(filter);
Matcher matcher = pattern.matcher(string);
boolean isMatch = matcher.find();
return isMatch;
}
// getters, setters and overrided hashCode, equal and toString methods omitted
}
The JPA class constructor CustomerOrder(Email email) is called by Quartz when a new email message is received. I tested this and this works. I have some customerorder records in my database.
Finally my JSF page:
<?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:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Test page</title>
</h:head>
<h:body>
<h:dataTable var="order" value="#{orderBean.orderList}" >
<h:column>
#{order.customerId}
</h:column>
</h:dataTable>
</h:body>
</html>
I am expecting this to output the customerId fields from thetable with customerorders in the database. However, it just returns an empty table.
I would at least expect that in my server terminal the Sysout messages from the bean are shown, but even these are not shown.
Question: What is wrong with my code, why are my database entry's not shown? How can I debug this problem?
using java 8, eclipse luna, tomcat 8 and mojarra 2.2.7;
after importing #ManagedBean from javax.faces.bean.ManagedBean instead of javax.annotations.ManagedBean, it works just fine.
I'm using JSF 2.2 with RequestScoped managebean. I'd like to update a Java List inside of Customers entity. When submitting, only info in Java List (List<'Phone >) is gone. I don't want to use SessionScoped. Could anyone share some tips or solve this issue?
My codes are shown here.
Customers Entity:
{ ..
#Column(name = "FIRSTNAME")
private String firstname;
#Column(name = "LASTNAME")
private String lastname;
...
#ElementCollection
#CollectionTable(name = "CUSTOMERS_Phone",
joinColumns = #JoinColumn(name = "CUSTOMERS_ID"))
#AttributeOverride(name = "teleNumbers",
column = #Column(name = "PHONE_NUMBER",length=30))
private List<Phone> phone;
..}
JSF Managebean:
#Named(value = "editCustomersBeanService")
#RequestScoped
public class EditCustomersBeanService implements Serializable {
/**
* Creates a new instance of EditCustomersBeanService
*/
#PostConstruct
public void init() {
ctx = FacesContext.getCurrentInstance();
customers =new Customers();
phones = new ArrayList<>();
customers.setPhone(phones);
}
public EditCustomersBeanService() {
}
#Inject
private BusinessSessionCustomers businessSSCustomers;
private int customerId;
private List<Phone> phones;
private Customers customers;
//setter, getter ...
//update to DB
public String updatedCustomers() {
System.out.println("customer Name: " + customers.getFirstname());
System.out.println("customer LastName: " + customers.getLastname());
System.out.print("List of Phones in updatedCustomers: ");
for (Phone ph : customers.getPhone()) {
System.out.print(ph.getPhoneType() + ", " + ph.getTeleNumbers());
}
businessSSCustomers.mergeToDB(customers);
return "customers";
}
..
}
CustomersEdit.xhtml:
<h:form>
...
<label for="Last Name">Last Name</label>
<h:inputText id="lastName" p:placeholder="Last Name"
value="#{editCustomersBeanService.customers.lastname}"/>
<ui:repeat var="phone" value="#{editCustomersBeanService.customers.phone}" varStatus="status">
<label for="phones">Phone: [#{status.index}]</label>
<h:selectOneMenu value="#{phone.phoneType}">
<f:selectItems value="#{editCustomersBeanService.phoneTypeList}"
itemLabel="#{editCustomersBeanService.phoneType}"
itemValue="#{editCustomersBeanService.phoneType}"/>
</h:selectOneMenu>
<h:inputText class=" form-control" value="#{phone.teleNumbers}" />
</ui:repeat>
<h:commandLink value="Save" action="#{editCustomersBeanService.updatedCustomers()}" />
…
</h:form>
Phone.java:
#Embeddable
public class Phone {
public enum PhoneType {
Home, Mobile, Work
}
#Enumerated(EnumType.STRING)
#Column(name = "PHONE_TYPE", length = 10)
private PhoneType phoneType;
#Column(name = "PHONE_NUM", length = 30)
private String teleNumbers;
//setter, getter
..
}
I have a table Users and Specializations in database
Users:
CREATE TABLE IF NOT EXISTS `ePrzychodnia`.`users` (
`id` INT NOT NULL AUTO_INCREMENT ,
`firstName` VARCHAR(45) NOT NULL ,
`lastName` VARCHAR(45) NOT NULL ,
`specialization_id` INT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `personalId_UNIQUE` (`personalId` ASC) ,
INDEX `fk_users_specializations1_idx` (`specialization_id` ASC) ,
CONSTRAINT `fk_users_specializations1`
FOREIGN KEY (`specialization_id` )
REFERENCES `ePrzychodnia`.`specializations` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Specializations:
CREATE TABLE IF NOT EXISTS `ePrzychodnia`.`specializations` (
`id` INT NOT NULL ,
`name` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `name_UNIQUE` (`name` ASC) )
ENGINE = InnoDB;
Entity class:
Users:
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "firstName")
private String firstName;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "lastName")
private String lastName;
#Basic(optional = false)
#JoinColumn(name = "specialization_id", referencedColumnName = "id")
#ManyToOne
private Specialization specializationId;
Specialization:
public class Specialization implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "name")
private String name;
#OneToMany(mappedBy = "specializationId")
private Collection<User> userCollection;
and I try create converter to one select menu in JSF:
SelectOneMenu:
<h:outputLabel for="specialization" value="#{msg.specialization}"/>
<p:selectOneMenu id="specialization" value="#{userMB.user.specializationId}" effect="fade" style="width:200px" converter="specializationConverter">
<f:selectItems value="#{specializationMB.allSpecialization}" var="specialization" itemValue="#{specialization}" itemLabel="#{specialization.name}"/>
</p:selectOneMenu>
<p:message for="specialization"/>
and Converter:
public class SpecializationConverter implements Converter{
private SpecializationDao specializationDao = new SpecializationDao();
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
Integer id = Integer.parseInt(value);
return specializationDao.find(id);
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
return ((Specialization) value).getId().toString();
}
}
But convertert dont work;/ I have a error:
WARNING: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
java.lang.NullPointerException
at pl.Project.dao.SpecializationDao.find(SpecializationDao.java:36)
at pl.Project.converter.SpecializationConverter.getAsObject(SpecializationConverter.java:29)
SpecializationDao:
#Stateless
public class SpecializationDao implements SpecializationDaoLocal {
#PersistenceContext
private EntityManager em;
private Specialization specialization;
public SpecializationDao() {
}
public SpecializationDao(Specialization specialization) {
this.specialization = specialization;
}
#Override
public Specialization find(int specializationId) {
return em.find(Specialization.class, specializationId);
}
#Override
public List<Specialization> findAllSpecialization() {
Query q = em.createNamedQuery("Specialization.findAll");
List<Specialization> specializations = q.getResultList();
return specializations;
}
}