Inheritance problem with HIBERNATE

Asked

Viewed 126 times

1

Well, my problem is this, I have an abstract class Official and two subclasses Attendant and Dentist inherited.

I also have a class User, which has as attributes login, ... , .... , ... and an employee attached to it.

My idea is that when for example we were registering a user was also informed an employee who would be linked to it. But as it was said, the working class is abstract and can be both attending and dentist. How could I solve this?

private Funcionario funcionario;

public Usuario(){

}

I then thought of instantiating the employee in the user class, and receiving a parameter in the constructor that would tell if the employee is an attendant or dentist. It worked, but it gave me another problem. As I am using Hibernate, when I made a select to fill in the user data and also of the respective functio the query gave Nullpointerexcpetion for I have not done for example:

private Funcionario funcionario;

public Usuario(){
    this.funcionario = new Funcionario();
}

So I’m in this problem right now, it’s kind of an early concept of O but I’ve never done anything like this so the problems, can anyone help me with this? Thank you guys!

1 answer

2

I believe that the implementation will depend a lot on the type of the project. I recommend a very didactic reading of the JPA Mini Book.I’m using in the example below the Single Table strategy:

Working class:

@Entity
@Table(name="funcionario")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="tipo", discriminatorType=DiscriminatorType.STRING)
public abstract class Funcionario implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "id")
    private Long id;

    @Column(name="nome")
    private String nome;

}

Dentist Class:

@Entity
@DiscriminatorValue(value="D")
public class Dentista extends Funcionario {

    private static final long serialVersionUID = 1L;

    @Column(name="registro")
    private String registro;

}

Class Attendant:

@Entity
@DiscriminatorValue(value="A")
public class Atendente extends Funcionario {

    private static final long serialVersionUID = 1L;

    @Column(name="turno")
    private String turno;

}

User class (here the mapping occurs - in this case, I believe it is Onetoone):

@Entity
public class Usuario {

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "funcionario")
    private Funcionario funcionario;

    public Usuario(Dentista dentista) {
        this.funcionario = dentista;
    }

    public Usuario(Atendente atendente) {
        this.funcionario = atendente;
    }

}
  • Just one note: If the column in the database is the same name as the attribute, you do not need to use the name of @Column

  • Well remembered! Thank Douglas.

Browser other questions tagged

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