Problem in creating entity with one-to-one relationship

Asked

Viewed 106 times

6

I created a project for testing, and I’m studying the creation of an entity with relationships, and in that I created two entities with this relationship below:

I am managing to create the entities, but not in the right way, using this class below:

package br.com.softplan.jpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import br.com.softplan.model.Pedido;

public class CadastraCategoriaJPA {

    public static void main(String[] args) {
        Pedido p = new Pedido();
        p.setNome_pedido("descrocao");

        EntityManager em = PersistenceUtil.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            em.persist(p);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        }
        PersistenceUtil.close(em);
        PersistenceUtil.close();
    }    
}

I want to know how to create the entities with the relationships by placing the values of the attributes of the two tables.

Table "request":

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nome_pedido;
@OneToOne
@JoinColumn(name = "endereco_id")
private Endereco enderecoEntrega;

Table "address":

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long endereco_id;
private String lougradouro;
@OneToOne(mappedBy = "enderecoEntrega")
private Pedido pedido;

That was an attempt but it didn’t work:

Pedido p = new Pedido();
Endereco end = new Endereco();

p.setNome_pedido("descrocao");

end.setLougradouro("hdsbcjhbsdjc");
end.setPedido(p);
  • 1

    You mentioned that you are still studying but nevertheless I suggest that you use the Java conventions in the codes. http://www.oracle.com/technetwork/java/codeconvtoc-136057.html

  • I think Daniela made it clear that the link did not answer her question, it’s just a suggestion to use the conventions that Java developers use to facilitate communication between them. And that’s a good suggestion, I’d say.

1 answer

1

Pedido p = new Pedido();
Endereco end = new Endereco();
end.setLogradouro("teste");
//set aqui o objeto completo do endereço
p.setEndereco(end);

Browser other questions tagged

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