Save a foreign key entity with Hibernate 4

Asked

Viewed 2,281 times

3

I’m starting to study Hibernate and I’d like to know what the method of saving an entity with a foreign key looks like. The following is an example of two entities:

Pupil:

@Entity(name = "aluno")
public class Aluno extends Pessoa{
    
    @Column(nullable=false)
    private String matricula;
    
    @Column(nullable=false)
    private String senha;

    public Aluno(String nome, String sexo, String dataNascimento, 
            String matricula, String senha) {
        super(nome, sexo, dataNascimento);
        this.matricula = matricula;
        this.senha = senha;
    }

Course:

@Entity(name = "curso")
public class Curso {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(nullable=false)
    private String nome;
    
    @Column(nullable=false)
    private int duracao;

    public Curso(String nome, int duracao) {
        this.nome = nome;
        this.duracao = duracao;
    }

Now the class containing foreign key:

@Entity(name = "matricula")
public class Matricula {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    
    @OneToOne
    @JoinColumn(name = "fk_curso",nullable=false)
    private Curso curso;

    @OneToOne
    @JoinColumn(name = "fk_aluno",nullable=false)
    private Aluno aluno;
    
    @Column(nullable=false)
    private String matricula;

    public Matricula(Curso curso, Aluno aluno, String matricula) {
        this.curso = curso;
        this.aluno = aluno;
        this.matricula = matricula;
    }

All classes have getters and setters (I didn’t put it in so it wouldn’t get too long)

I would like to know what would be the "save" method for enrollment. Thank you from now!

2 answers

2

Good afternoon everyone, I was having the same problem here!

Solved perfectly:

@OneToOne(cascade=CascadeType.ALL)

2

Good morning. The secret to persist an entity with foreign keys is not in the save method but in the mapping between entities. In order to be able to persist all objects by saving only the Enrollment object, you will need to change the mapping of the Course and Student attributes. You should be informed that when saving the Enrollment object the Course and Student objects will also be saved.

For this you must the following mapping:

    @OneToOne(cascade=CascadeType.ALL) //Com esse parâmetro na anotação @OneToOne você esta informando para hibernate que toda vez que você salvar uma matricula você vai salvar/Atualizar um Curso 
    @JoinColumn(name = "fk_curso",nullable=false)
    private Curso curso;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "fk_aluno",nullable=false)
    private Aluno aluno;

The "Cache" parameter has other values, so it guides you to a read in the doc from Hibernate.

Below is an example of saving method in Hibernate.

 Session sess = factory.openSession();
 Transaction tx;
 try {
     tx = sess.beginTransaction();
     //do some work
     tx.saveOrUpdate(obj);
     tx.commit();
 }
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 }
 finally {
     sess.close();
 }

Saveorupdate Hibernate

Good luck.

  • Thanks, it all worked out. It helped a lot, great explanation

  • Hello @Leonardo. You can indicate that a reply was useful by voting on it. If an answer solved your problem you should also accept it so that other users with the same problem know which solution you have just adopted.

  • That of Antonio Edmilson

Browser other questions tagged

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