如何使用 Hibernate 多对多将 jsp 页面中的多个选择标记中的数据保存到数据库

Posted

技术标签:

【中文标题】如何使用 Hibernate 多对多将 jsp 页面中的多个选择标记中的数据保存到数据库【英文标题】:How to save data from multiple select tag in jsp page to DB using Hibernate many-to-many 【发布时间】:2016-04-30 00:30:54 【问题描述】:

我想使用 hibernateuser 保存到数据库中,映射:ma​​ny-to-many

POJO:

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

技能.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>

<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

在选择标签中我从数据库中获取数据

<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>

问题: 当我填写输入并选择一些技能时,提交后,在表格中我成功获得了 id、姓名、电子邮件、密码,但技能显示如下:

如果我选择一项技能: [com.entity.Skills@60b7080b]

如果我选择两个技能: [com.entity.Skills@60b7080b, com.entity.Skills@5e0659ab]

所以我希望你清楚。

【问题讨论】:

电脑怎么会猜到你想显示什么?您需要告诉它要显示Skills 类的哪些属性。 我该如何解决这个问题,我尝试这样做: 但它不起作用,我认为问题就在这里,但我找不到解决方案: public List showUsers() List result = session.createCriteria(Users.class).list();返回结果; 如何遍历所有技能并打印每个技能所需的属性? 【参考方案1】:

感谢 Dragan Bozanovic 的帮助,但我自己找到了解决方案:

<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>

【讨论】:

是的,如果你有列表的属性,那么你必须迭代它们中的每一个以在屏幕上显示。否则,您将只有“属性”的“列表”引用对象。

以上是关于如何使用 Hibernate 多对多将 jsp 页面中的多个选择标记中的数据保存到数据库的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Hibernate 的条件中使用多对多关联中的索引列?

Hibernate:n-n关联关系

使用 Hibernate Criteria 查询多对多关系

hibernate多对多映射中间表有多余字段问题该如何映射

Hibernate 与同一实体的递归多对多关联

hibernate的映射之四(多对多双向关联)