"Error" CRUD Hibernate JAVA

3

Folks, I'm starting to learn how to use hibernate, and a kind of "error" occurred while a registry persisted. When registering an object player I must also pass the team of that player, however, the team is already registered in the database, so I should only pass the existing record until all is well, except that when I execute the persistence of the player it also persists a team again.

In short: When a player is registered, he also registers the team that was passed to that player, even though the team was already registered in the database. Can anyone help me with this?

Player Class:

public class Jogador {      
@Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "jogador_Cod")
    private int id;

    @Column(name="jogador_Nome", length=100,nullable=false)
    private String nome;

    @Column(name="jogador_DataNascimento" ,length=10,nullable=false)
    private String data_Nascimento;

    @Column(nullable=false, name="jogador_Salario")
    private double salario;

    @Column(nullable=false, name="jogador_Camisa")
    private int numeroCamisa;

    @Column(nullable=false, name="jogador_EmCampo")
    private boolean emCampo;

    @Column(nullable=false, name="jogador_cartaoAmarelo")
    private boolean cartaoAmarelo;

    @Column(nullable=false, name="jogador_qtdCartaoAmarelo")
    private int qtdCartaoAmarelo;

    @Column(nullable=false, name="jogador_qtdCartaoVermelho")
    private int qtdCartaoVermelho;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name="time_Cod")    
    private Time time;'}

Time Class:

public class Time {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="time_Cod")
private int id;

@Column(nullable=false,name="time_Nome",length=100)
private String nome;

@Column(nullable=false,name="time_Estado",length=100)
private String estado;

@Column(nullable=false,name="time_Pontos")
private int pontos;

@OneToMany(mappedBy="time")
private List<Jogador> jogadores;}

EDIT 1: Persistence Method

public static void main(String[] args) {                                    
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("conexaoDB");
    EntityManager em = emf.createEntityManager();
    EntityTransaction et = em.getTransaction();     
        try {
            et.begin();         
            //                  
            Time t = new Time();
            t.setEstado("PERNAMBUCO");
            t.setPontos(0);
            t.setNome("Sport Club do Recife");
            //
            Time t2 = new Time();
            t2.setEstado("SAO PAULO");
            t2.setPontos(0);
            t2.setNome("SANTOS");
            //
            Jogador j = new Jogador();
            j.setCartaoAmarelo(false);
            j.setData_Nascimento("29/02/9090");
            j.setEmCampo(false);
            j.setNome("Carlinhos Bala");
            j.setNumeroCamisa(10);
            j.setQtdCartaoAmarelo(3);
            j.setQtdCartaoVermelho(1);
            j.setSalario(1090);
            j.setTime(t);
            //
            em.persist(j);
            et.commit();                
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
        finally
        {
            em.close();
            emf.close();
        }       
}
    
asked by anonymous 09.09.2016 / 20:37

1 answer

2

This problem is happening because you are not passing Chave Primária of your Time that is already registered.

This would solve your problem:

Time t = new Time();
//Id do Pernambuco que é a chave primária
t.setId(1);
t.setNome("Pernambuco");

But note that if you pass a different name than the one in the bank it will be rewritten. This will happen because you are using cascade = CascadeType.ALL in your relationship with Time .

Recommendation:

Take out CascadeType.ALL of your relationship with Time and put it in the Players relationship:

Player:

@ManyToOne
@JoinColumn(name="time_Cod")    
private Time time;

Time:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "time", cascade = CascadeType.ALL)
private List<Jogador> jogadores;
    
09.09.2016 / 22:07