最近我开始使用hibernate。插入或更新我正在使用saveOrUpdate()
功能。
如果我更新一个条目我工作正常。但是,用新的入口hibernate生成一个Query。但表中没有任何内容更新。
我的情况是这样的,
我正在使用Many to One&两个表之间的一对多关系[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
。
但Expense
表cat_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.
答案 0 :(得分:1)
我不确定我是否了解所有内容,但我至少可以告诉您,您没有正确构建双向关联,您需要设置“链接的两侧”时构建对象图:
...
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);
有趣(或没有),我今天已经写了三次。