Ola sou iniciante em programação java estou tentando fazer meu primeiro cadastro…encontrei na web um jeito automatico de fazer os cadastros utilizando o persistencia criando uma classe persistente de dados e depois criando o jsf dessas classes…fiz 3 tables usuario, produto e venda e na venda tenho o campo total onde eu pego o valor unit do produto e multiplico pelo preco sóq criando dessa forma q eu fiz ele gera td automatico e a table de venda acaba q se tornando um cadastro tbm…por gerar automatico nao sei onde q eh feito o insert para eu tentar mudar o metodo e colocar ele multiplicando os valores…alguem conhece e pod me ajudar? vou colocar ele aqi…se alguem conhecer agradeço…
VendaController
@ManagedBean(name = "vendaController")
@SessionScoped
public class VendaController implements Serializable {
private Venda current;
private DataModel items = null;
private VendaJpaController jpaController = null;
private PaginationHelper pagination;
private int selectedItemIndex;
public VendaController() {
}
public Venda getSelected() {
if (current == null) {
current = new Venda();
selectedItemIndex = -1;
}
return current;
}
private VendaJpaController getJpaController() {
if (jpaController == null) {
jpaController = new VendaJpaController(Persistence.createEntityManagerFactory("VerVendasPU"));
}
return jpaController;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
@Override
public int getItemsCount() {
return getJpaController().getVendaCount();
}
@Override
public DataModel createPageDataModel() {
return new ListDataModel(getJpaController().findVendaEntities(getPageSize(), getPageFirstItem()));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Venda) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Venda();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getJpaController().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("VendaCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Venda) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getJpaController().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("VendaUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Venda) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
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 {
getJpaController().destroy(current.getIdVenda());
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("VendaDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getJpaController().getVendaCount();
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 = getJpaController().findVendaEntities(1, selectedItemIndex).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(getJpaController().findVendaEntities(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(getJpaController().findVendaEntities(), true);
}
@FacesConverter(forClass = Venda.class)
public static class VendaControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
VendaController controller = (VendaController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "vendaController");
return controller.getJpaController().findVenda(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 Venda) {
Venda o = (Venda) object;
return getStringKey(o.getIdVenda());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + VendaController.class.getName());
}
}
}
}
Entidade Venda
[code]
@Entity
@Table(name = "Venda", catalog = "cepein", schema = "")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Venda.findAll", query = "SELECT v FROM Venda v"),
@NamedQuery(name = "Venda.findByIdVenda", query = "SELECT v FROM Venda v WHERE v.idVenda = :idVenda"),
@NamedQuery(name = "Venda.findByIdProduto", query = "SELECT v FROM Venda v WHERE v.idProduto = :idProduto"),
@NamedQuery(name = "Venda.findByQtde", query = "SELECT v FROM Venda v WHERE v.qtde = :qtde"),
@NamedQuery(name = "Venda.findByDataVenda", query = "SELECT v FROM Venda v WHERE v.dataVenda = :dataVenda"),
@NamedQuery(name = "Venda.findByTotal", query = "SELECT v FROM Venda v WHERE v.total = :total")})
public class Venda implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "idVenda", nullable = false)
private Integer idVenda;
@Column(name = "idProduto")
private Produto idProduto;
@Column(name = "Qtde")
private Integer qtde;
@Column(name = "DataVenda")
@Temporal(TemporalType.DATE)
private Date dataVenda;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "Total", precision = 22)
private Double total;
public Venda() {
}
public Venda(Integer idVenda) {
this.idVenda = idVenda;
}
public Integer getIdVenda() {
return idVenda;
}
public void setIdVenda(Integer idVenda) {
this.idVenda = idVenda;
}
public Produto getIdProduto() {
return idProduto;
}
public void setIdProduto(Produto idProduto) {
this.idProduto = idProduto;
}
public Integer getQtde() {
return qtde;
}
public void setQtde(Integer qtde) {
this.qtde = qtde;
}
public Date getDataVenda() {
return dataVenda;
}
public void setDataVenda(Date dataVenda) {
this.dataVenda = dataVenda;
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idVenda != null ? idVenda.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 Venda)) {
return false;
}
Venda other = (Venda) object;
if ((this.idVenda == null && other.idVenda != null) || (this.idVenda != null && !this.idVenda.equals(other.idVenda))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entity.Venda[ idVenda=" + idVenda + " ]";
}
}
[/code]
VendaJpaController
public class VendaJpaController implements Serializable {
public VendaJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Venda venda) throws PreexistingEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(venda);
em.getTransaction().commit();
} catch (Exception ex) {
if (findVenda(venda.getIdVenda()) != null) {
throw new PreexistingEntityException("Venda " + venda + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Venda venda) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
venda = em.merge(venda);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = venda.getIdVenda();
if (findVenda(id) == null) {
throw new NonexistentEntityException("The venda with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Venda venda;
try {
venda = em.getReference(Venda.class, id);
venda.getIdVenda();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The venda with id " + id + " no longer exists.", enfe);
}
em.remove(venda);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public List<Venda> findVendaEntities() {
return findVendaEntities(true, -1, -1);
}
public List<Venda> findVendaEntities(int maxResults, int firstResult) {
return findVendaEntities(false, maxResults, firstResult);
}
private List<Venda> findVendaEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Venda.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Venda findVenda(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Venda.class, id);
} finally {
em.close();
}
}
public int getVendaCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Venda> rt = cq.from(Venda.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}