在Struts2 Action中更新实体

时间:2017-03-20 04:19:53

标签: hibernate jpa struts2

我正在尝试在Struts2 Action中加载一组实体,然后保存通过表单提交所做的任何更改。我正在使用paramsPrepareParams堆栈,并在提交表单时遇到问题。

我在下面添加了代码,显示了我的设置方式。问题在于,每当我尝试修改其中一个下拉列表以更新其中一个entity2实体上的entity1字段时,其余实体最终都会使用相同的值,即使我没有更改它们。

具有讽刺意味的是,如果我更改prepare方法以使用Entity1单独加载entity1ListgetEntityManager().find(...)个对象,则可以按预期工作

有人可以提供任何帮助吗?我正在使用Struts2 / Hibernate / JPA

ENTITY1:

@Entity
public class Entity1 {

    private Integer id;
    private Entity2 entity2;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name ="ID")
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "ENTITY_2_REF", referencedColumnName = "ID")
    public Entity2 getEntity2() {
        return entity2;
    }

    public void setEntity2(Entity2 entity2) {
        this.entity2 = entity2;
    }
}

ENTITY2:

@Entity
public class Entity2 {

    private Integer id;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name ="ID")
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
}

TestAction:

public class TestAction extends ActionSupport implements Preparable {

    private List<Entity1> entity1List;
    private Map<Integer, String> entity2Options;

    @Override
    public void prepare() throws Exception {
        if (savingData) {
            TypedQuery<Entity1> query = getEntityManager().createQuery("SELECT a FROM Entity1 a", Entity1.class);
            entity1List = query.getResultList();
        }
    }

    public String execute() {
        if(viewingData) {
            TypedQuery<Entity1> query = getEntityManager().createQuery("SELECT a FROM Entity1 a", Entity1.class);
            entity1List = query.getResultList();
            return "success";
        } else if (savingData) {
            beginTransaction();
            for(Entity1 e1 : entity1List) {
                getEntityManager().merge(e1);
            }
            commit();

            return "redirect";
        }

        return "success";
    }

    public Map<Integer, String> getEntity2Options() {
        Map<Integer, String> m = new LinkedHashMap<Integer, String>();
        m.put(1, "Test 1");
        m.put(2, "Test 2");
        m.put(3, "Test 3");
        return m;
    }

    public List<Entity1> getEntity1List() {
        return entity1List;
    }

    public void setEntity1List(List<Entity1> entity1List) {
        this.entity1List = entity1List;
    }
}

test.jsp的:

<s:form>
    <s:iterator value="entity1List" status="status">
        <s:select name="entity1List[%{#status.index}].entity2.id" list="entity2Options" theme="simple"/>
    </s:iterator>
</s:form>

0 个答案:

没有答案