Doubt with the treatment of a manyTomany and oneTomany scheme mixed

2

I'm doing an event management web project for class with java, jsp, hibernate h2 and maven. My question is, how do I associate users with the events and both with the table? I mean, I want the application to remember which user has registered to which event and its associated payment, counting on a user In addition to creating an event you can also attend it, there is also a boolean administrator attribute so that you are the only user that can delete other users or add them. The truth is that it is my first project and I am a bit involved with the topic, apart from the fact that the professors explain the minimum and doubts arise all the time, I hope you can help me.

  

Pojo Attend:

@Entity
@Table(name = "asistentes")
@AssociationOverrides({
        @AssociationOverride(name = "primaryKey.usuario", joinColumns = @JoinColumn(name = "idUsuario")),
        @AssociationOverride(name = "primaryKey.evento", joinColumns = @JoinColumn(name = "idEvento")) })
public class Asiste {

// clave primaria-id compuesta

private UsuarioEventoId primaryKey = new UsuarioEventoId();

// campos adicionales
@Column(name = "nombreEntidad")
private String nombreEntidad;

@Column(name = "nombreCuenta")
private String nombreCuenta;

@Column(name = "iban")
private String iban;

@Column(name = "numeroCuenta")
private String numeroCuenta;

@Column(name = "fechaPago")
//@Temporal(TemporalType.DATE)
@Type(type="date")
private Date fechaPago;
  

Pojo Event:

@Entity

@Table (name="events") public class Event {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "idEvento")
private long idEvento;

@Column(name = "nombreEvento")
private String nombreEvento;

@Column(name = "tipoEvento")
private String tipoEvento;

@Column(name = "descripcionEvento")
private String descripcionEvento;

@Column(name = "precioEvento")
private double precioEvento;

@Column(name = "fechaCreacion")
private Date fechaCreacion;

@Column(name = "fechaCelebracion")
@Type(type="date")
private Date fechaCelebracion;

// Los días que faltan para que se cumpla el evento
@Column(name = "diasRestantes")
private long diasRestantes;

@Column(name = "iva")
private double iva;

@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name = "usuario_id")
private Usuario usuario;

@OneToMany(mappedBy = "primaryKey.evento",fetch=FetchType.EAGER)
@Cascade(CascadeType.ALL)
@ElementCollection(targetClass=Integer.class)
private Collection<Asiste> listadoAsistentes;
  

User Pojo:

@Entity

@Table (name="users") public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "idUsuario")
private long idUsuario;

@Column(name = "nombreUsuario")
private String nombreUsuario;

@Column(name = "apellidosUsuario")
private String apellidosUsuario;

@Column(name = "contrasenia")
private String contrasenia;

@Column(name = "email")
private String email;

@Column(name = "administrador")
private boolean administrador;

@Column(name = "preguntaSecreta")
private String preguntaSecreta;

@Column(name = "respuestaSecreta")
private String respuestaSecreta;

// ¿Sería lo adecuado?
@Column(name = "sexo")
private String sexo;

// Primera relación 1 a * con la tabla Evento
@OneToMany(mappedBy="usuario",fetch=FetchType.EAGER)
@ElementCollection(targetClass=Integer.class)
private Collection<Evento> listadoEventos;

// Relación de 1 a * con la tabla Asiste
@OneToMany(mappedBy = "primaryKey.usuario",fetch=FetchType.EAGER)
@Cascade(CascadeType.ALL)
@ElementCollection(targetClass=Integer.class)
private Collection<Asiste> listadoAsistentes;
  

Pojo UsuarioEventoId (embeddable class)

@Embeddable
public class UsuarioEventoId implements Serializable {

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


    private Usuario usuario;


    private Evento evento;

    // Getters y Setters
    @ManyToOne
    @Cascade(CascadeType.ALL)
    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }
    @ManyToOne
    @Cascade(CascadeType.ALL)
    public Evento getEvento() {
        return evento;
    }

    public void setEvento(Evento evento) {
        this.evento = evento;
    }

    @Override
    public String toString() {
        return "UsuarioEventoId [usuario=" + usuario + ", evento=" + evento + "]";
    }
  

Servlet form User

protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("UTF-8");

        String nombreUsuario = request.getParameter("nombreUsuario");
        String apellidosUsuario = request.getParameter("apellidosUsuario");
        String contrasenia = request.getParameter("contrasenia");
        String email = request.getParameter("email");
        String preguntaSecreta = request.getParameter("preguntaSecreta");
        String respuestaSecreta = request.getParameter("respuestaSecreta");
        String sexo = request.getParameter("sexo");

        GestionUsuarios gestionUsuarios = new GestionUsuarios();

        // No tengo muy claro si con los campos a null funcionará correctamente
        // cuando se agreguen los objetos a la lista
        Usuario usuario = new Usuario(nombreUsuario, apellidosUsuario, contrasenia, email, false, preguntaSecreta,
                respuestaSecreta, sexo, null, null);

        gestionUsuarios.addUsuario(usuario);

        request.setAttribute("usuarios", gestionUsuarios.list());

        //response.sendRedirect("app/tablaUsuarios.jsp");

        //response.sendRedirect("app/tablaUsuarios.jsp");
        //Había que tener aquí un dispather para que la tabla se mostrara
        request.getRequestDispatcher("tablaUsuarios.jsp").forward(request, response);


    }
  

Event form Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse    response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    // doGet(request, response);

    String nombreEvento = request.getParameter("nombreEvento");
    String tipoEvento = request.getParameter("tipoEvento");
    String descripcionEvento = request.getParameter("descripcionEvento");
    // Hacer el parseDouble
    String precioEvento = request.getParameter("precioEvento");

    double precioParseado = 0;
    try {
        precioParseado = Double.parseDouble(precioEvento);
    } catch (NullPointerException npe) {

    } catch (NumberFormatException nfe) {

    }

    // Fecha de creación: debe aparecer automáticamente
    Date fechaCreacion = new Date();

    // Fecha de celebración
    String fechaCeleb = request.getParameter("fechaCelebracion");

    DateFormat formatoFecha = new SimpleDateFormat("dd/MM/yyyy");
    Date fechaCelebracion = null;
    try {
        fechaCelebracion = formatoFecha.parse(fechaCeleb);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // De momento los días restantes estarán a null hasta que me de tiempo a
    // implementarlo(resta de fechas)
    String iva = request.getParameter("iva");

    double ivaParseado = 0;
    try {
        ivaParseado = Double.parseDouble(iva);
    } catch (NullPointerException npe) {

    } catch (NumberFormatException nfe) {

    }

    GestionEventos gestionEventos = new GestionEventos();



    Evento evento = new Evento(nombreEvento, tipoEvento, descripcionEvento, precioParseado, fechaCreacion,
            fechaCelebracion, 0, ivaParseado, null, null);


    gestionEventos.addEvento(evento);

    request.setAttribute("eventos", gestionEventos.list());

    request.getRequestDispatcher("tabla.jsp").forward(request, response);

}
  

and Assist form Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub


    request.setCharacterEncoding("UTF-8");

    String nombreEntidad = request.getParameter("nombreEntidad");
    String nombreCuenta = request.getParameter("nombreCuenta");
    String iban = request.getParameter("iban");
    String numeroCuenta = request.getParameter("numeroCuenta");
    Date fechaPago = new Date();


    GestionAsistentes gestionAsistentes = new GestionAsistentes();

    // No tengo muy claro si con los campos a null funcionará correctamente
    // cuando se agreguen los objetos a la lista
    Asiste asistente = new Asiste(nombreEntidad, nombreCuenta, iban, numeroCuenta, fechaPago);

    gestionAsistentes.addAsistente(asistente);

    request.setAttribute("asistentes", gestionAsistentes.list());

    //response.sendRedirect("app/tablaUsuarios.jsp");

    //response.sendRedirect("app/tablaUsuarios.jsp");
    //Había que tener aquí un dispather para que la tabla se mostrara
    request.getRequestDispatcher("tablaAsiste.jsp").forward(request, response);


}
    
asked by Jose 25.05.2016 в 21:45
source

1 answer

0

The problem is that the mapping of the entities is incorrect.

Specifically in the mapping of the assistants within the pojo Evento.java you use @ElementCollection this type of mapping is used only when the referenced element type is a weak entity that depends on the primary one to exist (has no identity own), what comes to be, basic or embedded types ( embedabbles ) in the javadoc of the annotation.

This type of mapping arose with JPA 2 to facilitate 1-to-many relationships where the referenced element will never have its own identity and only has a reason to be associated with a strong entity. For example, a user's phones.

Keep in mind that the elements referenced to be embedded (with @Embbedable ) can not be entities (with @entity ) so they can not be persisted separately from the strong entity to which they are linked, nor be retrieved from the database independently.

In your case, removing the @ElementCollection event entity would be:

@Entity
@Table(name = "eventos") 
public class Evento {

    ...otros campos...

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "primaryKey.evento",fetch=FetchType.EAGER)
    private Collection<Asiste> listadoAsistentes;
}

Note: It is not recommended to do fetch EAGER of complete collections because you can get more database data than you planned.

The user entity would be:

@Entity
@Table(name = "usuarios") 
public class Usuario {

    ...otros campos...

    // Primera relación 1 a * con la tabla Evento
    @OneToMany(mappedBy="usuario",fetch=FetchType.EAGER)
    private Collection<Evento> listadoEventos;

    // Relación de 1 a * con la tabla Asiste
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "primaryKey.usuario",fetch=FetchType.EAGER)
    private Collection<Asiste> listadoAsistentes;

}
    
answered by 18.10.2016 в 09:32