[英]Hibernate One-to-Many Mapping Using Annotations; I'm trying to use foreign key association to save a user id in another table.
我无法完成这项工作。 我也尝试过使用联接表,但是结果是一样的。 我需要在表中显示的用户ID不需要。
这是我创建实体的方式。
对于User和UserRole,我使用了一个联接表,它可以工作。 我曾尝试对Commission进行相同的操作,但没有成功(联接表仍然为空),因此我尝试使用外键关联进行如下操作。
用户:
@Entity
@Table(name="USERS")
public class User implements Serializable{
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@NotEmpty
@Column(name="USERNAME", unique=true, nullable=false)
private String username;
@NotEmpty
@Column(name="PASSWORD", nullable=false)
private String password;
@NotEmpty
@Column(name="FIRST_NAME", nullable=false)
private String firstName;
@NotEmpty
@Column(name="LAST_NAME", nullable=false)
private String lastName;
@NotEmpty
@Column(name="EMAIL", nullable=false)
private String email;
@NotEmpty
@ManyToMany(targetEntity=UserRole.class, fetch = FetchType.LAZY)
@JoinTable(name = "USERS_USER_ROLE",
joinColumns = { @JoinColumn(name = "USER_ID") },
inverseJoinColumns = { @JoinColumn(name = "USER_ROLE_ID") })
private Set<UserRole> userRoles = new HashSet<UserRole>();
@OneToMany(fetch = FetchType.LAZY, mappedBy="user")
private Set<Commission> commissions;
//getters and setters
佣金:
@Entity
@Table(name="COMMISSIONS")
public class Commission implements Serializable{
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@NotEmpty
@Column(name="ORDER_NAME", unique=true, nullable=false)
private String orderName;
@NotEmpty
@Column(name="ORDER_DETAILS", unique=true, nullable=false)
private String orderDetails;
@Column(name="ORDER_STATUS", unique=true, nullable=false)
private String orderStatus;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID", nullable = false)
private User user;
//getters and setters
UserRole:
@Entity
@Table(name="USER_ROLE")
public class UserRole implements Serializable{
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="ROLE", length=15, unique=true, nullable=true)
private String role = UserRoleType.USER.getUserRoleType(); // getUserRoleType is defined in an enum with 'ADMIN', 'DBA', 'USER'
//getters and setters
在UserDAO和CommissionDAO中,我使用了SessionFactory来保存实体。
从由UserDAO和CommissionDAO扩展的抽象类中摘录。
@Autowired
private SessionFactory sessionFactory;
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
public void persist(T entity) {
getSession().save(entity);
}
当我创建一个新用户时,一切正常。 联接表中已添加了正确的ID。 但是...当我添加新的佣金时,佣金本身会添加到佣金表中,但user_id仍为null。
我是新来的冬眠者,有了我的这个“项目”,我想我可能会想不到的更多。
也许问题出在代码中的其他地方而不是这里?
无论如何,我有点束手无策,可以使用您的专业知识人员。 干杯!
感谢Rossi Robinsion。 就是这样
我错过了将用户与我的佣金控制器关联的想法。 这是以前。
@RequestMapping(value = { "/newcommission" }, method = RequestMethod.POST)
public String saveCommission(@Valid Commission commission, BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "commissioncreation";
}
if(!commissionService.isUserOrderNameUnique(commission.getId(), commission.getOrderName())){
FieldError orderNameError =new FieldError("commission","orderName",
messageSource.getMessage("non.unique.orderName",
new String[]{commission.getOrderName()}, Locale.getDefault()));
result.addError(orderNameError);
return "commissioncreation";
}
commissionService.saveCommission(commission);
model.addAttribute("success", "Your commission was successfully created.");
model.addAttribute("loggedinuser", getPrincipal());
return "commissioncreationsuccess";
}
这是之后。
@RequestMapping(value = { "/newcommission" }, method = RequestMethod.POST)
public String saveCommission(@Valid Commission commission, BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "commissioncreation";
}
if(!commissionService.isUserOrderNameUnique(commission.getId(), commission.getOrderName())){
FieldError orderNameError =new FieldError("commission","orderName",
messageSource.getMessage("non.unique.orderName",
new String[]{commission.getOrderName()}, Locale.getDefault()));
result.addError(orderNameError);
return "commissioncreation";
}
User user = userService.findByUsername(getPrincipal()); // associated the user properly.
commission.setUser(user);
commissionService.saveCommission(commission);
model.addAttribute("success", "Your commission was successfully created.");
model.addAttribute("loggedinuser", getPrincipal());
return "commissioncreationsuccess";
}
我不知道我怎么会错过这个...
谢了哥们!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.