最近,我开始使用休眠模式。插入或更新我正在使用saveOrUpdate()函数。
如果我更新条目,我可以正常工作。但是,使用新条目休眠会生成一个查询。但是表中没有任何更新。

我的情况就是这样

我正在使用两个表之间的多对一和一对多关系[Expense, Category]
为了更新或插入,我正在从中创建两个对象(Expense expense, Category category)
客户端。在服务器端,我将category对象设置为expense对象。

public void upDateExpenseTable(Expens expense, Category category) {

    expense.setCategory(category);
    Session session = Main.getSession();
    try{
        System.out.println("Inside Update Try Block");
        session = Main.getSession();
        Transaction tr = session.beginTransaction();
        session.saveOrUpdate(expense);
        tr.commit();

    }
    finally{
        session.close();
    }
}


对象结构就像catogery.catId, category.catName
expense.expnsId, expense.expnsName, expense.amount, expense.status, expense.userName

但是Expensecat_id中还有另一列。它是通过映射注释。但我在Expense实体中没有任何财产。
插入新数据时,我没有提供任何ID。

有什么建议么!!!

public class Expens implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int expnsId;
private int amount;
private String date;
private String status;
private String userName;

    @ManyToOne
@JoinColumn(name = "cat_id")
private Category category;
    //Setter Getter

}


分类类别

public class Category{
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int catId;
private String catName;

@OneToMany(targetEntity=Expens.class, mappedBy = "category", cascade = CascadeType.ALL, fetch=FetchType.EAGER)
private List<Expens> expenses;
}//Setters Getters ommited.

最佳答案

我不确定我是否了解所有内容,但我至少可以告诉您,您没有正确建立双向关联,在建立对象图时需要设置“链接双方”:

...
expense.setCategory(category);
category.getExpenses().add(expense);
...
session.saveOrUpdate(category);


通常,这是通过“链接管理”方法完成的,例如(在Category中):

@Entity
public class Category {

    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int catId;
    private String catName;

    @OneToMany(targetEntity=Expens.class, mappedBy = "category", cascade = CascadeType.ALL, fetch=FetchType.EAGER)
    private List<Expens> expenses = new ArrayList<Expens>();

    public void addToExpenses(Expense expense) {
        expenses.add(expense);
        expense.setCategory(this);
    }

    protected List getExpenses() { // protected to prevent direct access from outside the hierarchy
        return expenses;
    }

    protected void setExpenses(List expenses) { // protected to prevent direct access
        this.expenses = expenses;
    }

    //...
}


代码变成:

category.addToExpenses(expense);
session.saveOrUpdate(category);


有趣的是(或者不是),我今天已经写了三遍了。

资源资源


Hibernate核心文档

1.2.6. Working bi-directional links

10-01 23:25