"Error" CRUD Hibernate JAVA

Question:

Guys, I'm starting to learn how to use hibernate and there was a kind of "error" when persisting a record. When registering a player object, I must also pass that player's team, however, the team is already registered in the database, so I should only pass the existing record so far, that's ok, but when I run the player's persistence, it also persists a team again.

In summary: When a player is registered, it also registers again the team that was passed to that player, even though the team is 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();
        }       
}

Answer:

This problem is happening because you are not passing the 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 name different from the one on the bank, it will be rewritten. This will happen because you are using cascade = CascadeType.ALL in your relation to Time .

Recommendation:

Remove CascadeType.ALL from its relationship with the Time and place it in the relationship with Players:

Player:

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

Time:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "time", cascade = CascadeType.ALL)
private List<Jogador> jogadores;
Scroll to Top