Emprestimo e Itens de Emprestimo em JPA com JSF

40 views
Skip to first unread message

Lucas.Java

unread,
Dec 17, 2009, 3:27:56 PM12/17/09
to java.ce
Prezados,

Gostaria de uma auxilio em uma aplicação. Não consigo preecher os
itens. Estou utilizando jpa. Vejamos os codigo.

Classe Emprestimo Bean
package br.com.empresa.projeto.apresentacao.mBean.cadastro;

import java.util.ArrayList;
import java.util.List;

import javax.faces.model.SelectItem;

import br.com.empresa.projeto.apresentacao.mBean.CrudBean;
import br.com.empresa.projeto.comum.excecao.NegocioException;
import br.com.empresa.projeto.comum.modelo.Cd;
import br.com.empresa.projeto.comum.modelo.Cidade;
import br.com.empresa.projeto.comum.modelo.Cliente;
import br.com.empresa.projeto.comum.modelo.Emprestimo;
import br.com.empresa.projeto.comum.modelo.ItensEmprestimo;
import br.com.empresa.projeto.negocio.bo.cadastro.ClienteBO;
import br.com.empresa.projeto.negocio.bo.cadastro.EmprestimoBO;
import br.com.empresa.projeto.negocio.bo.cadastro.ItensEmprestimoBO;

public class EmprestimoBean extends CrudBean<Emprestimo> {

private ClienteBO clienteBO;

private EmprestimoBO emprestimoBO;

private ItensEmprestimoBO itensemprestimoBO;

private ItensEmprestimo itemEmprestimo; // <------ Item corrente

public ItensEmprestimo getItemEmprestimo() {
return itemEmprestimo;
}

public void setItemEmprestimo(ItensEmprestimo itemEmprestimo) {
this.itemEmprestimo = itemEmprestimo;
}

public EmprestimoBean() {
clienteBO = new ClienteBO();
emprestimoBO = new EmprestimoBO();
itensemprestimoBO = new ItensEmprestimoBO();


}

protected Class<Emprestimo> getClasse() {
return Emprestimo.class;
}

protected void incluir(Emprestimo emprestimo) throws NegocioException
{
emprestimoBO.incluir(emprestimo);
}

protected void alterar(Emprestimo emprestimo) throws NegocioException
{
emprestimoBO.alterar(emprestimo);
}

protected void excluir(Emprestimo emprestimo) throws NegocioException
{
emprestimoBO.excluir(emprestimo);
}

protected List<Emprestimo> buscar() throws NegocioException {
return emprestimoBO.buscarTodos();
}

public Long getCodigoCliente() {
if (getEntidade() != null && getEntidade().getCliente() != null
&& getEntidade().getCliente().getId() != null) {
return getEntidade().getCliente().getId();
}
return 0L;
}

public void setCodigoCliente(Long codigo) {
try {
Cliente cliente = clienteBO.buscar(codigo);
if (getEntidade() != null) {
getEntidade().setCliente(cliente);
}
} catch (NegocioException e) {
}
}

public List<SelectItem> getCliente() {
List<SelectItem> clientes = new ArrayList<SelectItem>();
clientes.add(new SelectItem(0, "Selecione"));

try {
for (Cliente cat : clienteBO.buscarTodos()) {
clientes.add(new SelectItem(cat.getId(), cat.getNome()));
}
} catch (NegocioException e) {
}

return clientes;
}

public void incluirItem() {
itemEmprestimo = new ItensEmprestimo();
}

public void setCd(Long codigo) {
try {
Cd cd = (Cd) itensemprestimoBO.buscar(codigo);
if (itemEmprestimo == null) {
incluirItem();
}

itemEmprestimo.setCd( cd );
} catch (NegocioException e) {
}
}

public void SalvarItem() throws NegocioException{
if (getEntidade() != null) {
getEntidade().getItens().add( itemEmprestimo );
}
}
}

Itens Emprestimo Bean

package br.com.empresa.projeto.apresentacao.mBean.cadastro;

import java.util.ArrayList;
import java.util.List;

import javax.faces.model.SelectItem;

import br.com.empresa.projeto.apresentacao.mBean.CrudBean;
import br.com.empresa.projeto.comum.excecao.NegocioException;
import br.com.empresa.projeto.comum.modelo.Cd;
import br.com.empresa.projeto.comum.modelo.Cidade;
import br.com.empresa.projeto.comum.modelo.ItensEmprestimo;
import br.com.empresa.projeto.comum.modelo.Uf;
import br.com.empresa.projeto.negocio.bo.cadastro.CdBO;
import br.com.empresa.projeto.negocio.bo.cadastro.ItensEmprestimoBO;

public class ItensEmprestimoBean extends CrudBean<ItensEmprestimo> {


private ItensEmprestimoBO itensemprestimoBO;

private CdBO cdBO;

public ItensEmprestimoBean() {
itensemprestimoBO = new ItensEmprestimoBO();
cdBO = new CdBO();
}

protected Class<ItensEmprestimo> getClasse() {
return ItensEmprestimo.class;
}

protected void incluir(ItensEmprestimo itensemprestimo ) throws
NegocioException {
itensemprestimoBO.incluir(itensemprestimo);
}

protected void alterar(ItensEmprestimo itensemprestimo) throws
NegocioException {
itensemprestimoBO.alterar(itensemprestimo);
}

protected void excluir(ItensEmprestimo itensemprestimo) throws
NegocioException {
itensemprestimoBO.excluir(itensemprestimo);
}

protected List<ItensEmprestimo> buscar() throws NegocioException {
return itensemprestimoBO.buscarTodos();
}

public Long getCodigoCd() {
if (getEntidade() != null && getEntidade().getCd() != null
&& getEntidade().getCd().getId() != null) {
return getEntidade().getCd().getId();
}
return 0L;
}

public void setCodigoCd(Long codigo) {
try {
Cd cd = cdBO.buscar(codigo);
if (getEntidade() != null) {
getEntidade().setCd(cd);
}
} catch (NegocioException e) {
}
}

public List<SelectItem> getCd() {
List<SelectItem> cds = new ArrayList<SelectItem>();
cds.add(new SelectItem(0, "Selecione"));

try {
for (Cd cat : cdBO.buscarTodos()) {
cds.add(new SelectItem(cat.getId(), cat.getNome()));
}
} catch (NegocioException e) {
}

return cds;
}
}

Entidade Emprestimo

package br.com.empresa.projeto.comum.modelo;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

import br.com.empresa.projeto.comum.anotacao.Label;

@Entity
@Table(name = "EMPRESTIMO")
public class Emprestimo implements Entidade {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "CD_EMPRESTIMO", nullable = false, length = 20)
private Long id;

@ManyToOne(optional = false)
private Cliente cliente;

@Temporal(TemporalType.DATE)
@Column(name = "DT_EMISSAO", nullable = false, length = 20)
private Date emissao;

@Temporal(TemporalType.DATE)
@Column(name = "DT_DEVOLUC", nullable = true, length = 20)
private Date devolucao;

@OneToMany(mappedBy = "emprestimo", fetch = FetchType.EAGER)
@Cascade(CascadeType.ALL)
private List<ItensEmprestimo> itens;

public List<ItensEmprestimo> getItens() {
if (itens == null) {
itens = new ArrayList<ItensEmprestimo>();
}
return itens;
}

public void setItens(List<ItensEmprestimo> itens) {
this.itens = itens;
}

public void adicionarItem(ItensEmprestimo item) {
if (item == null)
throw new IllegalArgumentException("Item nulo");

this.getItens().add(item);
}

public void removerItem(ItensEmprestimo item) {
if (item == null)
throw new IllegalArgumentException("Item nulo");

this.getItens().remove(item);
}

public Cliente getCliente() {
return cliente;
}

public void setCliente(Cliente cliente) {
this.cliente = cliente;
}

public Date getEmissao() {
return emissao;
}

public void setEmissao(Date emissao) {
this.emissao = emissao;
}

public Date getDevolucao() {
return devolucao;
}

public void setDevolucao(Date devolucao) {
this.devolucao = devolucao;
}

public Long getId() {
return id;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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;
Emprestimo other = (Emprestimo) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}

}

entidade itens do emprestimo

package br.com.empresa.projeto.comum.modelo;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import br.com.empresa.projeto.comum.anotacao.Label;

@Entity
public class ItensEmprestimo implements Entidade {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "CD_ITENS", nullable = false, length = 20)
private Long id;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "CD_PEDIDO", insertable = true, updatable = true)
@Label("Emprestimo")
private Emprestimo emprestimo;

@ManyToOne(cascade = CascadeType.ALL )
@JoinColumn(name = "CD_ITEM", insertable = true, updatable = true)
private Cd cd;

@Column(name = "QT_ITEM", nullable = false, length = 20)
private int quantidade;

@Column(name = "VL_TOTAL_ITEM", nullable = false, length = 20)
private double valorTotal;

public Emprestimo getEmprestimo() {
return emprestimo;
}

public void setEmprestimo(Emprestimo emprestimo) {
this.emprestimo = emprestimo;
}

public Cd getCd() {
return cd;
}

public void setCd(Cd cd) {
this.cd = cd;
}

public int getQuantidade() {
return quantidade;
}

public void setQuantidade(int quantidade) {
this.quantidade = quantidade;
}

public double getValorTotal() {
if (valorTotal == 0)
updateValue();
return valorTotal;
}

public void setValorTotal(double valorTotal) {
this.valorTotal = valorTotal;
}

public Long getId() {
return id;
}

@PrePersist
@PreUpdate
public void updateValue() {
if (cd != null)
valorTotal = quantidade * cd.getValor();
else
valorTotal = 0;
}

}

Emprestimo BO
package br.com.empresa.projeto.negocio.bo.cadastro;

import java.util.List;

import br.com.empresa.projeto.comum.excecao.NegocioException;
import br.com.empresa.projeto.comum.modelo.Emprestimo;
import br.com.empresa.projeto.comum.modelo.ItensEmprestimo;
import br.com.empresa.projeto.comum.utils.validacao.Validador;
import br.com.empresa.projeto.negocio.bo.BaseBO;

public class EmprestimoBO extends BaseBO<Emprestimo> {

public Emprestimo incluir(Emprestimo emprestimo) throws
NegocioException {
Validador.naoNulo(emprestimo, "Produto inválido!");
if (emprestimo.getEmissao() == null) {
throw new NegocioException("Emissao é Obrigatorio " + "!.");
}
if (emprestimo.getItens() == null) {
throw new NegocioException(
"É obrigatorio conter itens no emprestimo" + "!.");
}
return super.incluirComValidacao(emprestimo);
}

public Emprestimo alterar(Emprestimo emprestimo) throws
NegocioException {
return super.alterarComValidacao(emprestimo);
}

public void excluir(Emprestimo emprestimo) throws NegocioException {
super.excluirComValidacao(emprestimo);
}

public List<Emprestimo> buscarTodos() throws NegocioException {
return super.buscarTodos(Emprestimo.class);
}

public void adicionarItemPedido(Emprestimo emprestimo,
ItensEmprestimo item ) {
emprestimo.adicionarItem(item);
}

public void removeItemPedido(Emprestimo emprestimo, ItensEmprestimo
item) {
emprestimo.removerItem(item);
}

}

Itens Emprestimo BO

package br.com.empresa.projeto.negocio.bo.cadastro;

import java.util.List;

import br.com.empresa.projeto.comum.excecao.NegocioException;
import br.com.empresa.projeto.comum.modelo.Cliente;
import br.com.empresa.projeto.comum.modelo.ItensEmprestimo;
import br.com.empresa.projeto.comum.utils.validacao.Validador;
import br.com.empresa.projeto.negocio.bo.BaseBO;
import br.com.empresa.projeto.persistencia.dao.OperadoresJPQL;

public class ItensEmprestimoBO extends BaseBO<ItensEmprestimo> {

public ItensEmprestimo incluir(ItensEmprestimo itensemprestimo)
throws NegocioException {
Validador.naoNulo(itensemprestimo, "Produto inválido!");
return super.incluirComValidacao(itensemprestimo);
}

public ItensEmprestimo alterar(ItensEmprestimo itensemprestimo)
throws NegocioException {
return super.alterarComValidacao(itensemprestimo);
}

public void excluir(ItensEmprestimo itensemprestimo) throws
NegocioException {
super.excluirComValidacao(itensemprestimo);
}

public List<ItensEmprestimo> buscarTodos() throws NegocioException {
return super.buscarTodos(ItensEmprestimo.class);
}
public List<ItensEmprestimo> buscar(Long id) throws NegocioException
{
return super.buscarComUmFiltro(ItensEmprestimo.class, "pedido",
OperadoresJPQL.IGUAL, id);
}

}

Já estou com duas semanas, alguém poderia me ajudar?

Grato!

Alexei Barbosa de Aguiar

unread,
Dec 17, 2009, 3:35:50 PM12/17/09
to jav...@googlegroups.com
S� faltou dizer que problema est� acontecendo.

Lucas.Java escreveu:
> Prezados,
>
> Gostaria de uma auxilio em uma aplica��o. N�o consigo preecher os

> Validador.naoNulo(emprestimo, "Produto inv�lido!");
> if (emprestimo.getEmissao() == null) {
> throw new NegocioException("Emissao � Obrigatorio " + "!.");


> }
> if (emprestimo.getItens() == null) {
> throw new NegocioException(

> "� obrigatorio conter itens no emprestimo" + "!.");

> Validador.naoNulo(itensemprestimo, "Produto inv�lido!");


> return super.incluirComValidacao(itensemprestimo);
> }
>
> public ItensEmprestimo alterar(ItensEmprestimo itensemprestimo)
> throws NegocioException {
> return super.alterarComValidacao(itensemprestimo);
> }
>
> public void excluir(ItensEmprestimo itensemprestimo) throws
> NegocioException {
> super.excluirComValidacao(itensemprestimo);
> }
>
> public List<ItensEmprestimo> buscarTodos() throws NegocioException {
> return super.buscarTodos(ItensEmprestimo.class);
> }
> public List<ItensEmprestimo> buscar(Long id) throws NegocioException
> {
> return super.buscarComUmFiltro(ItensEmprestimo.class, "pedido",
> OperadoresJPQL.IGUAL, id);
> }
>
> }
>

> J� estou com duas semanas, algu�m poderia me ajudar?
>
> Grato!
>
> --
>
> You received this message because you are subscribed to the Google Groups "java.ce" group.
> To post to this group, send email to jav...@googlegroups.com.
> To unsubscribe from this group, send email to javace+un...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/javace?hl=en.
>
>
>
>

--
Alexei Barbosa de Aguiar
Verde Tecnologia
+55(85)8776.0801
+55(85)3474.5040
Skype: alexeiaguiar

Lucas.Java

unread,
Dec 17, 2009, 6:55:54 PM12/17/09
to java.ce
Prezados,

Preciso preencher os itens de emprestimo para gravar o emprestimo.

On 17 dez, 17:35, Alexei Barbosa de Aguiar <ale...@verde.com.br>
wrote:

> > For more options, visit this group athttp://groups.google.com/group/javace?hl=en.

Felipe Thomas

unread,
Dec 18, 2009, 6:03:26 AM12/18/09
to jav...@googlegroups.com
Lucas.Java, deixe-me ver se entendi.
Você gostaria de passar um objeto Emprestimo com um campo contendo uma lista de Itens e ao chamar um save do JPA passando o Emprestimo já gravar automaticamente os Itens.

É isso?

Confirma aê.



2009/12/17 Lucas.Java <lucaschav...@gmail.com>

Lucas.Java

unread,
Dec 18, 2009, 7:58:18 AM12/18/09
to java.ce

Issso mesmo Felipe! Apenas não sei como implementar este metodo na
classe Bean para poder assim chama-lo no cadastro do jsf.


On 18 dez, 08:03, Felipe Thomas <felipece...@gmail.com> wrote:
> Lucas.Java, deixe-me ver se entendi.
> Você gostaria de passar um objeto Emprestimo com um campo contendo uma lista
> de Itens e ao chamar um save do JPA passando o Emprestimo já gravar
> automaticamente os Itens.
>
> É isso?
>
> Confirma aê.
>

> 2009/12/17 Lucas.Java <lucaschavesrica...@gmail.com>

> ...
>
> mais »

Reply all
Reply to author
Forward
0 new messages