How to search the bank with three types of user?

Asked

Viewed 60 times

0

Hello I’m doing a college project, it’s an internship site project, it has to be developed in Java WEB with database. It has three types of user, the student, the company and the administrator. I wonder if there is any way at the time of logging in I do not have to search the three tables.

I was thinking of making a user table, in which you have the email, the password, his type (1-Adm, 2-student...) and finally a field of the user id in your table. Then I would do the query in the user table, and from the type of it, I would discover the table in which it meets and with the id found it.

So I’m doing two searches. there’s another way to do it with just one?

Thank you!

2 answers

2

You can join the tables at the time of the query:

select *
from Usuario usu
left join Administrador adm on  adm.id   = usu.id
                            and usu.tipo = 1
left join Aluno alu on  alu.id   = usu.id
                    and usu.tipo = 2

1


In your User class, set the attribute "Usuario type" or something of the type and when instantiating the object set its type searching the values in an Enum. Sort of like:

public enum TipoUsuario {
    ADMIN, ALUNO, SISTEMA
}

Then when you need to check the type of permission you can refer to the type of permission with a case switch for example:

public static void main(String[] args) {
    Usuario usuario = new Usuario();
    usuario.setNome("Banana");
    usuario.setTipoPermissao(TipoUsuario.ADMIN);

    switch (usuario.getTipoPermissao()) {
    case ADMIN:
        System.out.println("Usuario Administrador.");
        break;
    case ALUNO:
        System.out.println("Usuario Aluno.");
        break;
    case SISTEMA:
        System.out.println("Usuario Sistema.");
        break;
    default:
        System.out.println("Quem diabos é esse cara?");
        break;
    }
}

All this without having to change table structure, when you want to change the type just call the user method.setTipoPermission and change to the type you want.

  • 1

    This may be an acceptable alternative if there are no different specific fields for each user type, or if the number of specific fields is small enough; for more complex situations, the use of multiple tables may become a better alternative. As always, it depends heavily on the situation.

Browser other questions tagged

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