How to search for ID’s in the bank and display the names on the screen?

Asked

Viewed 360 times

2

In my JSF + Primefaces project, I have the following entities:

@Entity
@Table(name = "geracao")
public class Geracao {

    @Getter
    @Setter
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Getter
    @Setter
    @NotBlank(message = "Nome não pode estar em branco.")
    @Pattern(regexp = "[A-z]*", message = "Atenção, digite somente letras")
    @Size(max = 20, message = "Máximo de 20 caracteres permitidos.")
    @Column(length = 20, nullable = false)
    private String nome;

    @Getter
    @Setter
    @Min(1)
    @Max(7)
    private Integer numero;

    @Getter
    @Setter
    @Column(name = "total_pokemons", nullable = false)
    private Integer totalPokemons;

    public Geracao() {

    }

}

@Entity
@Table(name = "habilidade", uniqueConstraints = @UniqueConstraint(columnNames = { "nome" }))
public class Habilidade {

    @Getter
    @Setter
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Getter
    @Setter
    @NotBlank(message = "Nome não pode estar em branco.")
    @Pattern(regexp = "[A-z]*", message = "Atenção, digite somente letras")
    @Size(max = 20, message = "Máximo de 20 caracteres permitidos.")
    @Column(length = 20, nullable = false)
    private String nome;

    @Getter
    @Setter
    @NotBlank
    @Size(max = 150, message = "Máximo de 150 caracteres permitidos.")
    @Column(length = 150, nullable = false)
    private String descricao;

    @Getter
    @Setter
    @NotBlank
    @Size(max = 150, message = "Máximo de 150 caracteres permitidos.")
    @Column(name = "texto_in_game", length = 150, nullable = false)
    private String textoInGame;

    @Getter
    @Setter
    @Column(length = 150, name = "efeito_secundario", nullable = true)
    private String efeitoSecundario;

    @Getter
    @Setter
    @ManyToOne
    private Geracao geracao;

    public Habilidade() {

    }

}

I have a relationship ManyToOne in Skill to register a Generation. The field generation_id was created correctly by Hibernate in the table Habilidade. I’m trying to implement on my screen a autoComplete and I read that the attribute completMethod is responsible for calling the method that will load the objects on the screen. How can I create a method in my Ability controller that looks only for Generation ID’s but click on the screen the Generations names so I can select one ? I want to search for ID’s to be a lighter consultation at the bank.

1 answer

1

Dear Douglas, first check whether you actually generated in the bank the foreign key of the generation table, in the skill table, to ensure the relationship. If it did not generate, use the "@Joincolumn" annotation before the declaration of the "private Generation" variable. As for the method, you could use a list method, I am attaching one that I use, in a Generic DAO, which serves to put the objects of a class in a list, normally I use this method to fill the combobox. but I think nothing prevents you from using in auto complete. Follow the code.

public List<Entidade> listar() {
    Session sessao = HibernateUtil.getFabricaDeSessoes().openSession();
    try {
        Criteria consulta = sessao.createCriteria(classe);
        List<Entidade> resultado = consulta.list();
        return resultado;
    } catch (RuntimeException erro) {
        throw erro;
    } finally {
        sessao.close();
    }
}

Bean method

@PostConstruct
public void listar() {
    try {
        ClienteDAO clienteDAO = new ClienteDAO();
        clientes = clienteDAO.listar();
    } catch (RuntimeException erro) {
        Messages.addFlashGlobalError("Ocorreu um erro ao tentar listar os clientes");
        erro.printStackTrace();
    }
}

Method that creates session factory `import org.hibernate.Sessionfactory; import org.hibernate.boot.registry.Standardserviceregistrybuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.Serviceregistry;

public class Hibernateutil { private Static Sessionfactory manufactureSessons = creatFabricaDessons();

public static SessionFactory getFabricaDeSessoes() {
    return fabricaDeSessoes;
}

private static SessionFactory criarFabricaDeSessoes() {
    try {
        Configuration configuracao = new Configuration().configure();

        ServiceRegistry registro = new StandardServiceRegistryBuilder()
                .applySettings(configuracao.getProperties()).build();

        SessionFactory fabrica = configuracao.buildSessionFactory(registro);

        return fabrica;
    } catch (Throwable ex) {
        System.err
                .println("A fábrica de sessões não pode ser criada." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}`
  • Thank you, what’s the point ?

  • The session, serves to open a session of Hibernate to access the data of the database and through the Criteria tbm of Hibernate, makes the search in the database and stores in the variable result.

  • As I use the dependency injection, I’ll need it anyway ?

  • In your case also he looks for a specific id right? I want him to search all.

  • About the addiction injection I can’t tell you.

  • Really, the method is looking for a specific id. I’m sorry I made the wrong method. I’ll edit and put the correct method. "list".

  • You can post your getFabricaDessodes method() ?

Show 2 more comments

Browser other questions tagged

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