Working with associative tables

I want to add to a table, the users who have registered a team. So that in the future you can list all the teams of a certain user.

However I have the following problem: in my table persona_time I can not get the ID of who is creating the team nor the ID of the team that is being created

The class that performs the team creation and the TimeBean:

@ManagedBean(name = "TimeMB")
@SessionScoped
public class TimeBean implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Time time = new Time();
    private TimeDAO dao = new TimeDAO();
    private Pessoa_Time pessoaTime = new Pessoa_Time();
    private Pessoa_TimeDAO ptdao = new Pessoa_TimeDAO();

    public TimeBean(){}

    public void cadastrar() {
        getDao().cadastrar(getTime());
        getPtdao().cadastrar(getPessoaTime());
    }

    public Time getTime() {
        return time;
    }

    public void setTime(Time time) {
        this.time = time;
    }

    public TimeDAO getDao() {
        return dao;
    }

    public void setDao(TimeDAO dao) {
        this.dao = dao;
    }

    public Pessoa_TimeDAO getPtdao() {
        return ptdao;
    }

    public void setPtdao(Pessoa_TimeDAO ptdao) {
        this.ptdao = ptdao;
    }

    public Pessoa_Time getPessoaTime() {
        return pessoaTime;
    }

    public void setPessoaTime(Pessoa_Time pessoaTime) {
        this.pessoaTime = pessoaTime;
    }
}

LoginBean:

@ManagedBean(name = "LoginMB")
@ViewScoped
public class LoginBean {

    private Pessoa pessoa = new Pessoa();
    private PessoaDAO pessoaDAO = new PessoaDAO();

    // Metodo para efetuar login na aplicação
    public String efetuaLogin() {

        // Vai imprimir no console o nome do usuario logado
        System.out.println("Fazendo login do usuário " + this.pessoa.getNomeUsuario());

        // facesContext e utilizado para pegar o nome da pagina
        FacesContext context = FacesContext.getCurrentInstance();
        boolean existe = new PessoaDAO().existe(this.pessoa);

        if (existe) {

            // Se usuario existir, armazena o usuario em usuarioLogado e mantem na sessão
            // Depois redireciona para a pagina seguinte

            context.getExternalContext().getSessionMap().put("usuarioLogado", this.pessoa);
            return "cadastrarTime?faces-redirect=true";
        }

        // Caso não exista, exibe a mensagem
        // Redireciona o usuario paga a pagina seguinte

        context.getExternalContext().getFlash().setKeepMessages(true);
        context.addMessage(null, new FacesMessage("Usuário não encontrado"));
        return "login?faces-redirect=true";
    }

    public String deslogar() {

        // Metodo para deslogar o usuario
        // Remove o usuariologado da SessionMap

        FacesContext context = FacesContext.getCurrentInstance();
        context.getExternalContext().getSessionMap().remove("usuarioLogado");

        // Depois de remover ele e redirecionado para a pagina seguinte

        return "login?faces-redirect=true";

    }

    public Pessoa getPessoa() {
        return pessoa;
    }

    public void setPessoa(Pessoa pessoa) {
        this.pessoa = pessoa;
    }

    public PessoaDAO getPessoaDAO() {
        return pessoaDAO;
    }

    public void setPessoaDAO(PessoaDAO pessoaDAO) {
        this.pessoaDAO = pessoaDAO;
    }

}

Person_time

@Entity
public class Pessoa_Time implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @ManyToOne
    @PrimaryKeyJoinColumn(name="id_pessoa", referencedColumnName="id_pessoa")
    private Pessoa pessoa;
    @ManyToOne
    @PrimaryKeyJoinColumn(name="id_time", referencedColumnName="id_time")
    private Time time;

    public Pessoa_Time(){}

    public Pessoa_Time(Pessoa_Time pt){
        this.id = pt.getId();
        this.pessoa = pt.getPessoa();
        this.time = pt.getTime();
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public Pessoa getPessoa() {
        return pessoa;
    }
    public void setPessoa(Pessoa pessoa) {
        this.pessoa = pessoa;
    }
    public Time getTime() {
        return time;
    }
    public void setTime(Time time) {
        this.time = time;
    }

    @Override
    public String toString() {
        return "Pessoa_Time [id=" + id + ", pessoa=" + pessoa + ", time=" + time + "]";
    }
}

Time:

@Entity
public class Time implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column (name="id_Time")
    private int id;
    @Column(nullable=false)
    private String nome;
    @Column(nullable=false)
    private String senhaTime;
    @OneToMany(mappedBy="time",cascade=CascadeType.ALL)
    private List<Pessoa_Time> pessoas;
    @OneToMany(mappedBy="time",cascade=CascadeType.ALL)
    private List<Pessoa_Time> campeonatos;

    public Time(){}

    public Time(Time time){
        this.id = time.getId();
        this.nome = time.getNome();
        this.senhaTime = time.getSenhaTime();
        this.pessoas = time.getPessoas();
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public List<Pessoa_Time> getPessoas() {
        return pessoas;
    }

    public void setPessoas(List<Pessoa_Time> pessoas) {
        this.pessoas = pessoas;
    }

    public List<Pessoa_Time> getCampeonatos() {
        return campeonatos;
    }

    public void setCampeonatos(List<Pessoa_Time> campeonatos) {
        this.campeonatos = campeonatos;
    }

    public String getSenhaTime() {
        return senhaTime;
    }

    public void setSenhaTime(String senhaTime) {
        this.senhaTime = senhaTime;
    }

    @Override
    public String toString() {
        return "Time [id=" + id + ", nome=" + nome + ", senhaTime=" + senhaTime + ", pessoas=" + pessoas
                + ", campeonatos=" + campeonatos + "]";
    }


}

TimeDAO:

public class TimeDAO {

    private EntityManager em;


    public TimeDAO() {
        setEm(JPAUtil.getEntityManager());
    }

    public void cadastrar(Time time){
        getEm().getTransaction().begin();
        getEm().persist(time);
        getEm().getTransaction().commit();
    }


    public List<Time> listaTodosTimes(){
        Query q = em.createQuery("select t from Time t");       
        List<Time> times = q.getResultList();
        return times;
    }

    public void atualizar(Time time){
        getEm().getTransaction().begin();
        getEm().merge(time);
        getEm().getTransaction().commit();
    }

    public void remover(Time time){
        getEm().getTransaction().begin();
        getEm().find(Time.class, time.getId());
        getEm().persist(time);
        getEm().getTransaction().commit();
    }

    public EntityManager getEm() {
        return em;
    }
    public void setEm(EntityManager em) {
        this.em = em;
    }
}

Person:

@Entity
public class Pessoa implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column (name="id_Pessoa")
    private Integer id;

    @Column()
    private String nomeUsuario;

    @Column()
    private String senhaUsuario;

    @Column()
    private String nomeCompleto;

    @Column()
    private String email;

    @Column()
    private Integer idade;

    @OneToMany(mappedBy="pessoa",cascade=CascadeType.ALL)
    private List<Pessoa_Time> times;

    public Pessoa (){}

    public Pessoa (Pessoa pessoa){
        this.id = pessoa.getId();
        this.nomeUsuario = pessoa.getNomeUsuario();
        this.senhaUsuario = pessoa.getSenhaUsuario();
        this.nomeCompleto = pessoa.getNomeCompleto();
        this.email = pessoa.getEmail();
        this.idade = pessoa.getIdade();
    }



    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNomeUsuario() {
        return nomeUsuario;
    }

    public void setNomeUsuario(String nomeUsuario) {
        this.nomeUsuario = nomeUsuario;
    }

    public String getNomeCompleto() {
        return nomeCompleto;
    }

    public void setNomeCompleto(String nomeCompleto) {
        this.nomeCompleto = nomeCompleto;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getIdade() {
        return idade;
    }

    public void setIdade(Integer idade) {
        this.idade = idade;
    }

    public List<Pessoa_Time> getTimes() {
        return times;
    }

    public void setTimes(List<Pessoa_Time> times) {
        this.times = times;
    }

    public String getSenhaUsuario() {
        return senhaUsuario;
    }

    public void setSenhaUsuario(String senhaUsuario) {
        this.senhaUsuario = senhaUsuario;
    }

    @Override
    public String toString() {
        return "Pessoa [id=" + id + ", nomeUsuario=" + nomeUsuario + ", senhaUsuario=" + senhaUsuario
                + ", nomeCompleto=" + nomeCompleto + ", email=" + email + ", idade=" + idade + ", times=" + times + "]";
    }
}

Person:

public class PessoaDAO {

    private EntityManager em;


    public PessoaDAO() {
        setEm(JPAUtil.getEntityManager());
    }

    public void cadastrar(Pessoa pessoa){
        getEm().getTransaction().begin();
        getEm().persist(pessoa);
        getEm().getTransaction().commit();
    }

    public void atualizar(Pessoa pessoa){
        getEm().getTransaction().begin();
        getEm().merge(pessoa);
        getEm().getTransaction().commit();
    }

    public List<Pessoa> listaTodasPessoas(){
        Query q = em.createQuery("select p from Pessoa p");     
        List<Pessoa> pessoas = q.getResultList();
        return pessoas;
    }

    // Metodo que vai verificar se os dados informados pelo usuario são validos

    public boolean existe(Pessoa pessoa) {

        // Realizar uma consulta com os parametros informados pelo usuario

        String consulta = "select u from Pessoa u where u.nomeUsuario = :pUsuario and u.senhaUsuario = :pSenha";
        Query query=getEm().createQuery(consulta);

        query.setParameter("pUsuario", pessoa.getNomeUsuario());
        query.setParameter("pSenha", pessoa.getSenhaUsuario());

        // Se for verdadeiro, resultado recebe a pessoa

        try {
            Pessoa resultado = (Pessoa) query.getSingleResult();
        } catch (NoResultException ex) {
            return false;
        }

        em.close();

        return true;
    }

    public void removerPessoa(Pessoa pessoa){
        getEm().getTransaction().begin();
        getEm().find(Pessoa.class, pessoa.getId());
        getEm().remove(pessoa);
        getEm().getTransaction().commit();  
    }


    public EntityManager getEm() {
        return em;
    }
    public void setEm(EntityManager em) {
        this.em = em;
    }
}
Author: Rafael Augusto, 2016-07-04

1 answers

Try the following.

Instead of in person

@OneToMany(mappedBy="pessoa",cascade=CascadeType.ALL)
private List<Pessoa_Time> times;

Create a

@ManyToMany
@JoinTable(name = "times_pessoas")
private List<Pessoa_Time> times;

And in team instead of:

@OneToMany(mappedBy="time",cascade=CascadeType.ALL)
private List<Pessoa_Time> pessoas;

Shout

@ManyToMany(mappedBy = "times")
private List<Pessoa_Time> pessoas;

With this the JPA will create and control the entity times_people it is not necessary to create the Class Persone_time.

 1
Author: Marcelo, 2016-07-04 17:04:04