Inheritance problem with HIBERNATE

1

Well, my problem is this: I have an abstract Employee class and two Attendant and Dentist subclasses that inherit from employee.

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

My idea is that when, for example, we were to register a user, we would also be informed of an employee who would be linked to him. But as it has been said, the employee class is abstract and can be both attendant 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. That worked, but gave me another problem. As I am using hibernate, when I made a select to fill in the user data and also the respective employee the query gave NullPointerExcpetion because I did not do for example:

private Funcionario funcionario;

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

So I'm in this problem today, it's a concept that kind of started OO, but I've never done anything like that, so can anybody help me with this? Thank you guys!

    
asked by anonymous 27.11.2016 / 23:51

1 answer

2

I believe the implementation will depend very much on the type of the project. I recommend a very didactic reading of JPA Mini Book . I am using the example below the Single Table strategy:

Employee 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 think it's 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;
    }

}
    
28.11.2016 / 13:53