【发布时间】:2014-12-07 20:17:35
【问题描述】:
在保存表单中的一些数据时,我还需要将 FK 添加到 Record 表中。 FK 是 User.Id。 我知道如何从表单的输入字段中保存数据,但是如何将 FK(int 值)设置为此:
@ManyToOne
@JoinColumn(name = "id")
@Cascade({CascadeType.ALL})
private User user;
有没有办法检索与登录用户相关的对象并制作如下内容:record.setUser(user)?
我用谷歌搜索了它,但我没有找到如何实现这一点。
这是我的实体类。
@Entity
public class Record implements java.io.Serializable{
@Id
@GeneratedValue
private int recordId;
private String recordName;
private String recordComment;
private Date recordDate;
private Integer price;
@ManyToOne
@JoinColumn(name = "userId", insertable = true, updatable = false)
@Cascade({CascadeType.ALL})
private User user;
......
}
@Entity
@Table(name = "system_user")
public class User implements java.io.Serializable{
@Id
@GeneratedValue
private int userId;
@NotEmpty
@Email
private String email;
@Size(min=2, max=30)
private String name;
private String enabled;
@NotEmpty
private String password;
private String confirmPassword;
@Enumerated(EnumType.STRING)
@Column(name = "user_role")
private Role role;
@OneToMany(fetch = FetchType.EAGER,mappedBy = "user", orphanRemoval=true)
@Cascade({CascadeType.ALL})
private List<Record> records;
public void addToRecord(Record record) {
record.setUser(this);
this.records.add(record);
}
....
}
这就是我将数据保存到数据库的方式:
@RequestMapping(value = "/protected/add", method = RequestMethod.POST)
public String addCost (@ModelAttribute("record") Record record,HttpSession session){
User user = userManager.getUserObject(userManager.getUserId(session.getAttribute("currentUser").toString()));
user.addToRecord(record);
recordService.addRecord(record);
return "redirect:/protected/purse";
}
道:
public void addRecord(Record record) {
sessionFactory.getCurrentSession().save(record);
}
更新:问题已部分解决,上面的代码对我来说很好。
【问题讨论】:
-
用户对象将包含记录对象的列表/集,这意味着您需要创建第一个用户对象,然后在用户对象中设置所有记录,然后保存用户对象,您的问题将解决。如果您的用户对象为空,则无法继续。
-
我添加了以下代码:
public void addToRecord(Record record) { record.setUser(this); this.records.add(record); } User user = new User(); user.setId(1); user.setName("admin"); ... some other setters user.addToRecord(record); record.setUser(user); recordService.addRecord(record);但 FK 没有保存,我也没有收到任何错误消息。 -
我已经修复它:只需将 @JoinColumn(name = "userId", insertable = false, updatable = false) 更改为 @JoinColumn(name = "userId", insertable = true, updatable = false) )
标签: java sql spring hibernate spring-mvc