2

Can someone please help me in resolving this. I am trying to create a page for Display, Edit and delete data from UserGroup (a MySQL DB table) with below structure in a JSF2.0 (xhtml page) . The problem I'm having is with the data actually getting displayed as objects of UserGroup table instead of the readable values from these columns. I tried out various sample solutions available for CRUD web application but not getting anywhere, sure i am missing the overall understanding of displaying and then editing the row data. However my create works fine. Do I need to write converters for displaying correct value?

Additional info

  • Glassfish v3.1.2
  • JPA/Eclipselink v2.1
  • MySQLDB
  • JSF2.0
  • Eclipse Juno SR2

UserGroup Table

  1. rowId (Auto Generated)
  2. groupId (foreign key for Group Id in Group table)
  3. username (foreign key for Username in User table)

Output I'm getting right now

Users's and their group.
Row Id    Group Id              Username 
9         model.Group@647d73bf  model.User@683a3423  
13        model.Group@2192bac5  model.User@2823ecbb  

XHTML code

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets">
<f:metadata>
    <f:viewParam name="userId" value="#{loginBean.username}"></f:viewParam>
</f:metadata>
<ui:composition>
    <h:head>
        <meta http-equiv="Content-Type"
            content="text/html; charset=ISO-8859-1" />
        <h1>Users's and their group.</h1>
        <title>Displaying Users and their Groups</title>
    </h:head>
    <h:body>
        <h:form id="form">
            <h:dataTable value="#{userGroupManagedBean.userGroup}" var="item">
                <h:column>
                    <f:facet name="header"> Row Id</f:facet> #{item.rowId}
</h:column>
                <h:column>
                    <f:facet name="header"> Group Id</f:facet> #{item.group}
</h:column>
                <h:column>
                    <f:facet name="header"> Username</f:facet> #{item.user}
</h:column>
            </h:dataTable>
        </h:form>
    </h:body>
</ui:composition>
</html>

*Managed Bean Class

package beans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
//import javax.faces.model.DataModel;
//import javax.faces.model.ListDataModel;

import model.UserGroup;

import ejb.UserGroupDaoBean;

@ManagedBean(name = "userGroupManagedBean", eager = true)
@SessionScoped
public class UserGroupManageBean implements Serializable {

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

    @EJB
    private UserGroupDaoBean uGDB;
    // private DataModel<UserGroup> userGroup;
    private List<UserGroup> userGroup;
    private UserGroup currentUserGroup;
    public String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getGroupId() {
        return groupId;
    }

    public void setGroupId(int groupId) {
        this.groupId = groupId;
    }

    public int groupId;

    // public void setUserGroup(DataModel<UserGroup> userGroup) {
    // this.userGroup = userGroup;
    // }

    public void setUserGroup(List<UserGroup> userGroup) {
        this.userGroup = userGroup;
    }

    public UserGroup getCurrentUserGroup() {
        return currentUserGroup;
    }

    @PostConstruct
    public void init() {

        getUserGroup();
    }

    public List<UserGroup> getUserGroup() {

        List<UserGroup> myAllUserGroups = new ArrayList<UserGroup>(
                uGDB.getAllUserGroups());

        return myAllUserGroups;
    }

    // public DataModel<UserGroup> getUserGroup() {
    // userGroup = new ListDataModel<UserGroup>(uGDB.getAllUserGroups());
    // System.out.println(userGroup);
    // return userGroup;
    // }

    // public String delete() {
    // UserGroup myUserGroup = userGroup.getRowData();
    // uGDB.deleteUserGroup(myUserGroup);
    // getUserGroup();
    // return
    // "displayUserGroup.jsf?faces-redirect=true&amp;includeViewParams=true";
    // }

    public String delete(UserGroup currentUserGroup) {
        userGroup.remove(currentUserGroup);
        getUserGroup();
        return "displayUserGroup.jsf?faces-redirect=true&amp;includeViewParams=true";
    }

    // public String edit(){
    // currentUserGroup = userGroup.getRowData();
    // System.out.println("And the current user group data is:" +
    // currentUserGroup);
    // getUserGroup();
    // return
    // "editUserGroup.jsf?faces-redirect=true&amp;includeViewParams=true";
    // }

    public String save() {

        uGDB.updateExistingUserGroup(currentUserGroup);

        getUserGroup();
        return "displayUserGroup.jsf?faces-redirect=true&amp;includeViewParams=true";
    }

    public String cancel() {
        // getUserGroup();
        return "displayUserGroup.jsf?faces-redirect=true&amp;includeViewParams=true";
    }

    public void setCurrentUserGroup(UserGroup currentUserGroup) {
        this.currentUserGroup = currentUserGroup;
    }
}

Controller Class

package ejb;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateful;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import javax.persistence.PersistenceContext;

import model.Group;
import model.User;
import model.UserGroup;

@Stateful
@LocalBean
public class UserGroupDaoBean {
    @PersistenceContext(unitName = "myPU")
    private EntityManager entityManager;

    public UserGroupDaoBean() {

    }

    public UserGroup createNewUserGroup(int groupId, String username) {

        UserGroup newUserGrp = new UserGroup();

        User myUsr;
        myUsr = entityManager.find(User.class, username);
        newUserGrp.setUser(myUsr);

        Group myGrp;
        myGrp = entityManager.find(Group.class, groupId);
        newUserGrp.setGroup(myGrp);

        saveNewUsrGrp(newUserGrp);
        return newUserGrp;
    }

    private void saveNewUsrGrp(UserGroup usrGrp) {
        entityManager.persist(usrGrp);
        entityManager.flush();
    }

    public boolean checkUsertoGroup(String username, int groupId) {

        Group chkGrp;
        chkGrp = entityManager.find(Group.class, groupId);

        User chkUsr;
        chkUsr = entityManager.find(User.class, username);

        if (chkGrp != null) {

            if (chkUsr != null) {

                try {
                    entityManager.createNamedQuery("findGroupsbyUser")
                            .setParameter("username", chkUsr)
                            .setParameter("groupId", chkGrp).getSingleResult();
                    System.out.println("UserGroup already exists");
                    return false;
                } catch (NoResultException e) {
                    return true;
                }

            }
            System.out.println("User doesn't exist");
            return false;
        }
        System.out.println("Group doesn't exist");

        return false;

    }

    public void deleteUserGroup(UserGroup userGroup) {
        userGroup = entityManager.merge(userGroup);
        entityManager.remove(userGroup);
    }

    public UserGroup update(UserGroup userGroup) {

        UserGroup myUserGroup = entityManager.merge(userGroup);

        return entityManager.merge(myUserGroup);
    }

    public UserGroup updateExistingUserGroup(UserGroup userGroup){
        UserGroup myExistingUsrGrp = update(userGroup);
        return myExistingUsrGrp;
    }

    @SuppressWarnings("unchecked")
    public List<UserGroup> getAllUserGroups() {

        try {
            Query query = entityManager.createNamedQuery("findAllUserGroup");
            List<UserGroup> result = (List<UserGroup>) query.getResultList();

            return result;

        } catch (NoResultException e) {
            System.out.println("No Result found");
            return null;
        }
    }

    public boolean validateGroup(User username) {

        Group groupId = entityManager.find(Group.class, 1);

        try {
            UserGroup myGroupId = (UserGroup) entityManager
                    .createNamedQuery("findAdminGroupId")
                    .setParameter("username", username)
                    .setParameter("groupId", groupId).getSingleResult();

            if (myGroupId != null) {
                System.out.println("This user is admin!!!");
                return true;
            }

        } catch (NoResultException e) {
            return false;
        }

        System.out.println("This user is not admin");
        return false;
    }

UserGroup POJO

package model;

import java.io.Serializable;
import javax.persistence.*;


/**
 * The persistent class for the UserGroup database table.
 * 
 */
@NamedQueries({

    @NamedQuery(name = "findGroupsbyUser", query = "Select ug.group from UserGroup ug where ug.user=:username AND ug.group=:groupId"),

    @NamedQuery(name = "findAllUserGroup", query="Select ug from UserGroup ug"),

    @NamedQuery(name = "findAdminGroupId", query = "Select ug from UserGroup ug where ug.user=:username AND ug.group=:groupId"),


})
@Entity
@Table(name="usergroup")
public class UserGroup implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="RowId" )
    private int rowId;

    //bi-directional many-to-one association to Group
    @ManyToOne
    @JoinColumn(name="groupId")
    private Group group;

    //bi-directional many-to-one association to User
    @ManyToOne
    @JoinColumn(name="username")
    private User user;

    public UserGroup() {
    }

    public int getRowId() {
        return this.rowId;
    }

    public void setRowId(int rowId) {
        this.rowId = rowId;
    }

    public Group getGroup() {
        return this.group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    public User getUser() {
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}
sup
  • 105
  • 1
  • 4
  • 17

1 Answers1

1

You are passing the userGroup's group and user objects to the JSF, not values. You probably want to pass item.group.id and item.user.id or their equivalents.

Chris
  • 20,138
  • 2
  • 29
  • 43
  • Sorry I didn't understand. Do i have to pass the Group ID from Group table and Username from User table? How will I do that? Because currently objects are returned like this from the UserGroup table Can you please elaborate a little. – sup Mar 31 '13 at 18:01
  • This isn't raw data from the database, you are dealing with a list of userGroup java objects. As such, when you use item.group, you are getting a group java object - not the foreign key database value you seemed to expect. You will need to change the object model, the query or get the values you want to display from the user and group java objects directly. – Chris Apr 01 '13 at 00:59
  • I understood the part that its returning ojects of UserGroup type but not able to figure out how to return the results as normal database values instead of UserGroup objects. Can you please give some hint may be in form of code snippet or any article/link i can refer to. This would be really great help because I am completely stuck with this. – sup Apr 01 '13 at 12:47
  • Ok. NAILED IT!!. :D Got this idea to create a View of this table. Thanks for pointing me to right direction!! :) – sup Apr 01 '13 at 17:15