0

I want to save user into database using hibernate, mapping : many-to-many

POJO's :

Users.java

@Entity
@Table(name = "users_db")
public class Users implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_user", unique = true, nullable = false)
private long id;

@Column(name = "userName_db")
private String userName;

@Column(name = "email_db")
private String Email;

private String password;

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "userskill", joinColumns = {
        @JoinColumn(referencedColumnName = "id_user", nullable = false) }, inverseJoinColumns = {
                @JoinColumn(referencedColumnName = "id") })
private Set<Skills> skills = new HashSet<Skills>();
// getters ans setters

Skills.java

@Entity
@Table(name = "skillsDB", uniqueConstraints = @UniqueConstraint (columnNames ="typeSkill") )
public class Skills implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "typeSkill")
private String typeSkill;

@ManyToMany(mappedBy = "skills")
private Set<Users> users = new HashSet<Users>();
// getters and setters

addUserServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    UserService userService = new UserServiceImpl();

    Users user = new Users();

    user.setUserName(request.getParameter("UserName"));
    user.setEmail(request.getParameter("Email"));
    user.setPassword(request.getParameter("Password"));

    Set<Skills> skillSet = new HashSet<Skills>();

    for (int i = 0; i < request.getParameterValues("skills").length; i++) {
        skillSet.add(new Skills(request.getParameterValues("skills")[i]));
    }
    user.setSkills(skillSet);
    userService.add(user);
    request.setAttribute("usersList", userService.showUsers());
    this.getServletContext().getRequestDispatcher("/addUser.jsp").forward(request, response);

}

UsersDAOImpl.java

public List<Users> showUsers() {

    List<Users> result = session.createCriteria(Users.class).list();
    return result;

}

Hibernate Configuration

<hibernate-configuration>

<session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/dictionnaire</property>
    <property name="connection.username">root</property>
    <property name="connection.password">mosab</property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <property name="use_sql_comments">true</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">update</property>

    <!-- Names the annotated entity class -->
    <mapping resource="com.entity.Users" />
    <mapping resource="com.entity.Skills" />

</session-factory>

addUser.jsp

In select tag I get data from database

<form action="adduser" method="post">
    <table>
        <tr>
            <td><label for="name">User name :* </label></td>
            <td><input type="text" name="UserName" /></td>
        </tr>
        <tr>

            <td><label for="Email">Email :* </label></td>
            <td><input type="text" name="Email" /></td>
        </tr>
        <tr>
            <td><label for="Password">Password :*</label></td>
            <td><input type="password" name="Password" /></td>
        </tr>
        <tr>
            <td><label for="skills">skills :</label></td>
            <td><select name="skills" multiple="multiple">
                    <c:forEach var="item" items="${skills }">
                        <option value="${item.typeSkill}" ><c:out value="${item.typeSkill}"/></option>
                    </c:forEach>
            </select></td>  
        </tr>
        <tr>
            <td><input type="submit" name="Save" /></td>
        </tr>
    </table>
</form>
<table>
    <thead>
        <tr>
            <th>Id User</th>
            <th>User name</th>
            <th>password</th>
            <th>email</th>
            <th>Skills</th>
        </tr>
    </thead>
    <tbody>
        <c:forEach var="item" items="${usersList}">
            <tr>
                <td><c:out value="${item.id}" /></td>
                <td><c:out value="${item.userName}" /></td>
                <td><c:out value="${item.password}" /></td>
                <td><c:out value="${item.email}" /></td>
                <td><c:out value="${item.skills}" /></td>
            </tr>
        </c:forEach>
    </tbody>
</table>

problem : when I fill inputs and I choose some skills, after submit, In the table I get id, name, email, password successfully,but skills apears like this :

If I choose one skill : [com.entity.Skills@60b7080b]

If I choose two skills : [com.entity.Skills@60b7080b, com.entity.Skills@5e0659ab]

So I hope that is clear for you.

3
  • How could computer guess what you want to display? You need to tell it which properties of the Skills class to show. Commented Jan 23, 2016 at 13:25
  • How can I solve this, I try to do : <td><c:out value="${item.skills.typeSkill}" /></td> but it does not work, I think the problem is here but I cant found the solution : public List<Users> showUsers() { List<Users> result = session.createCriteria(Users.class).list(); return result; Commented Jan 24, 2016 at 10:41
  • How about iterating through all of the skills and printing the desired property from each skill? Commented Jan 24, 2016 at 11:05

1 Answer 1

1

Thank you Dragan Bozanovic for your help, but I found the solution myself:

<c:forEach var="item" items="${usersList}">
                <tr>
                    <td><c:out value="${item.id}" /></td>
                    <td><c:out value="${item.userName}" /></td>
                    <td><c:out value="${item.password}" /></td>
                    <td><c:out value="${item.email}" /></td>
                    <td><c:forEach var="skill" items="${item.skills}">
                            <c:out value="${skill.typeSkill}"/> 
                        </c:forEach></td>
                </tr>
    </c:forEach>
Sign up to request clarification or add additional context in comments.

1 Comment

Yeap, if you have a property of lists, then you have to iterate each of them to Show on the screen. or else, you'll just have the "list" reference object of the "property".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.