Create Foreign Key Hibernate

Asked

Viewed 58 times

0

Solved and edited the correct line:

I cannot include a invoice with the customer’s id. In this case the customer may have several tax notes assigned to him.

I am able to register the NF correctly, but does not show the number of the customer that this invoice is linked, in the BD appears the id, number of nf, date and value but does not show the number of the customer to whom it belongs.

In the customer’s registration appears the field invoice number and the value is null.

Follow the files:

Notafiscal

@Entity
public class NotaFiscal implements Serializable{

private static final long serialVersionUID = 1L;

 @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    private String numero;
    private Double valor;
    @Temporal(TemporalType.DATE)
    private Calendar data = Calendar.getInstance();


    @ManyToOne
    @JoinColumn(name="id_cliente")
    private Cliente cliente;

   public NotaFiscal() {

   }

//include the client getter and Setter in the notafiscal file

Client

@Entity
 public class Cliente {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;        
private String nome;    
private String sobrenome;
@Email
@NotBlank
@Column(unique=true)
private String email;
private String senha;    
private String cpf;    
private String cep;    
private String endereco;    
private String numero;    
private String bairro;    
private String cidade;    
private String estado;
private String ddd;    
private String celular;

@OneToMany(mappedBy="cliente")
  private Set<NotaFiscal> notas;


public Cliente() {
}

Notafiscalbean

@Model
public class NotaFiscalBean {


private NotaFiscal notaFiscal = new NotaFiscal();
@Inject
private NotaFiscalDAO notaFiscalDAO;
@Inject
private ClienteDAO clienteDAO;

private Cliente cliente = new Cliente();
private Long idCliente;




@Transactional
public void gravar() {

     Cliente cliente = clienteDAO.buscaPorId(idCliente);
     notaFiscal.setCliente(cliente );
     notaFiscalDAO.adiciona(notaFiscal);

    clienteDAO.save(cliente);

    this.notaFiscal = new NotaFiscal();

    this.setCliente(new Cliente());

    idCliente = null;
}

HTML

<h:form>
    <div class="form-group row">
        <label for="nomecliente" class="col-sm-8 col-form-label">
            Identificação do Cliente (digite o numero do cliente)</label>
        <div class="col-sm-10"><br></br>
            <h:inputText  id="nomecliente" value="# 
               {notaFiscalBean.idCliente}" type="number" class="form- 
       control"  
       a:autofocus="true" />
        </div>
    </div>

<h:commandButton value="Cadastrar" type="submit" class="btn btn-warning" 
   action="#{notaFiscalBean.gravar}"></h:commandButton>

</h:form>

noteFiscalDAO

public class NotaFiscalDAO implements Serializable {

private static final long serialVersionUID = 1L;


@PersistenceContext
private EntityManager manager;

public void adiciona(NotaFiscal nota) {
    manager.persist(nota);
}

public List<NotaFiscal> listaTodos() {
    CriteriaQuery<NotaFiscal> query = 
manager.getCriteriaBuilder().createQuery(NotaFiscal.class);
    query.select(query.from(NotaFiscal.class));

    List<NotaFiscal> lista = manager.createQuery(query).getResultList();

    return lista; 
}

public int contaTodos() {
    long result = (Long) manager.createQuery("select count(n) from 
     NotaFiscal n").getSingleResult();

    return (int) result;
}

public List<NotaFiscal> listaTodosPaginada(int firstResult, int maxResults) 
{
    CriteriaQuery<NotaFiscal> query = 
     manager.getCriteriaBuilder().createQuery(NotaFiscal.class);
    query.select(query.from(NotaFiscal.class));

    List<NotaFiscal> lista = 
   manager.createQuery(query).setFirstResult(firstResult)
            .setMaxResults(maxResults).getResultList();

    return lista;
}

 }

Clientele looking for the client id in the BD

public Cliente buscaPorId(Long id) {

    Cliente cliente = manager.find(Cliente.class, id);

    return cliente;
}

1 answer

1


You are doing a wrong mapping, when you say that a customer can have multiple tax bills so the correct one is the invoice having only one customer and not one customer list, instead of using Onetomany (many customers may have one note), use Manytoone (many notes can have the same account), would look like this:

Invoice entity:

@ManyToOne
@JoinColumn(name="id_cliente")
private Cliente cliente

Client entity

@OneToMany(mappedBy="cliente")
private Set<NotaFiscal> notas;

Note: to map the notes in the client, I recommend using the data structure Set instead of List, because it already guarantees that there will not be two identical entities in Collection.

  • Thank you very much for the return Adriano, I understood, I made the changes and I can register the invoice in the comic book there was no mistake, but when consulting the invoice table the field id_client appears null and I believe that should appear the customer id, wouldn’t that be it. You could tell me where I’m going wrong?

  • Post the complete method you are using to save.

  • thanks Adriano, I edited the post and included the files if you need anything else let me know that I post.

  • Hi Adriano solved. After a lot of testing and changing I found the solution. NULL was caused by the missing customer getter and Setter in the notafiscal file. The rest with the changes you guided me worked perfectly. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.