【问题标题】:Saving in a web application保存在 Web 应用程序中
【发布时间】:2013-07-31 18:39:30
【问题描述】:

我有一个 Web 应用程序(使用 Vaadin、Hibernate 和 Postgres 数据库),用户可以在其中向某个表添加数据。当用户向此表中添加项目时,他们被要求输入名称、日期,并从表中选择所有相关产品。当他们单击保存时,我可以将名称和日期保存到数据库中,但是无法从表中抓取项目并将它们放入要添加的集合中。表的 bean 类如下所示:

/** Created by Hibernate **/
public class BeanClass implements Serializable {
    private String name;
    private Date date;
    private Set relatedProducts = new HashSet(0);
    .
    .
    .
    }

我用来保存用户想要添加的项目的代码是:

BeanClass toAdd = new BeanClass();
Set temp = null

/** There is a table where the user can select all the products they want to add 
* When they select an item it goes to another table, so what I am doing here
* is adding looping through latter table and adding all the items they selected
* to a set (supposedly i think this should work
**/
for (Object item : table) {
  temp.add(table.getContainerProperty("id", item));
}

toAdd.setName(nameField.getValue()); //I have input fields for the name and date
toAdd.setDate(dateField.getValue());
toAdd.setRelatedProducts(temp);

hbsession.save(toAdd);

当用户单击保存时,名称和日期被添加到表中,但相关产品没有添加到关系表中(在数据库中)。我已经研究过休眠中的级联和逆向,我认为我将不得不使用这些,但不太了解如何使用。

【问题讨论】:

    标签: java hibernate postgresql set vaadin


    【解决方案1】:

    您的相关产品集是什么数据类型?是不是另一个 Bean,那你就得定义一个 OneToMany 注解。

    在将 Set 写入数据库之前是否已对其进行了调试?

    您实际上不需要遍历整个表来获取选定的值。您可以通过 table.getValue() 获取选择的项目

    getValue()

    获取选定的项目 id 或在多选模式下获取一组选定的 id。

    如果表中的数据类型与 Bean 中的数据类型相同,则

    toAdd.setRelatedProducts(table.getValue());
    

    应该够了。

    【讨论】:

    • relatedProucts 应该是一个整数元组 ((1,2),(1,4),(1,6)),所以当用户点击保存时,它会在 1 中添加 3 个关系。 vaadin a table 属于组件类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    相关资源
    最近更新 更多