How do I search for the ID's in the bank and display the names on the screen?

1

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 ManyToOne relationship in Ability to register a Generation . The generation _id field was created correctly by Hibernate in the Habilidade table. I'm trying to implement a autoComplete on my screen and I've read that the completMethod attribute is responsible for calling the method that will load the objects on the screen. How can I create a method in my Skill controller that searches only for Generation IDs but clicks the Generations names on the screen so I can select one? I want to search for ID's to be a lighter query in the bank.

    
asked by anonymous 23.11.2016 / 16:51

1 answer

0

Dear Douglas, first check to see if you actually generated the foreign key of the generation table in the database in the ability table to ensure the relationship. If not generated, use anotation "@JoinColumn" before declaration of the variable "private Geração geracao".   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, I usually use this method to populate the comboBox. but I think nothing prevents you from using the 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 the 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 = class =

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);
    }
}'
    
23.11.2016 / 18:22