"Error" CRUD Hibernate JAVA

Asked

Viewed 107 times

3

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

Summarizing: When a player is registered, he also re-registers the team that was passed to that player, even though the team was already registered in the database. Can someone help me with that?

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();
        }       
}
  • Publish the player’s persistence methods, @Junior

  • Added Mark, the first 2 times objects were the ones I entered in the bank, as you can see, when I create the player object I just step a team and it turns out I persisted the record again

  • Post the error that occurs please.

  • So Douglas, it’s not a mistake in itself, the problem is, I registered the 2 teams that are in the Dadosfutebol class, when registering the player I pass one of these 2 teams, so far so good, including the record is completed, however, when entering the player, even if the team is already registered in the database Hibernate itself generates another record or I have 1. Sport 2. Sao Paulo, and when registering the player Hibernate includes a new, 3.Sao Paulo

  • Have you tried to take the cascade = CascadeType.ALL of your Manytoone?

  • @Junior, in this method you do not persist time, you just urge them.

Show 1 more comment

1 answer

2


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

That would solve your problem:

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

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

Recommending:

Take off the CascadeType.ALL of its relationship with Time and put it in the relationship with Players:

Gambler:

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

Team:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "time", cascade = CascadeType.ALL)
private List<Jogador> jogadores;
  • Hi, @Diegoaugusto, He’s using the strategy=GenerationType.IDENTITY to the jogador, soon would not need to pass parameters by setter, not there is the problem!

  • but it is strange that he uses the strategy=GenerationType.IDENTITY for player and strategy=GenerationType.AUTO for time

  • @Marcossousa If he wants to save a player with a team he needs to set the team ID, because if he does not set how the relationship will be mounted?

  • got it, but the code you put in is only saying that the "t" team has the id = 1; the code of the method it published is correct, it passes the team it wants to persist in j.setTime(t); He says that player "j" has a "t" team, with all its attributes including the id. but the order it persists is incorrect, as is the opening of the transaction.

  • He passes a team, but there’s no way of knowing which team he is, because he doesn’t pass the Primary Key. He only passes a team name, so the Team note is like CascadeType.ALL and it does not pass a valid ID a new team is created with a new ID

  • I agree with you about cascade = CascadeType.ALL

  • you simulated the example? I will refactor it and reach a more faithful conclusion.

  • @Marcossousa Yes. At first I thought the main problem was Cascade, but I saw that it was just a detail. If it does not pass the id it will never persist the team with the players correctly

  • 1

    Guys thank you very much, sorry for the delay of the feedback but I only just arrived from college, Diego’s answer solved my problem, was exactly this the mistake, it was more a discussion than a mistake because I forgot to pass also the ID. Thank you very much to all of you!!

Show 5 more comments

Browser other questions tagged

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