我有一个问题要问:
我必须通过 user.id -> user_login.user_id 将表 user 和 user_login 加入 OneToOne。
问题是当我执行 .updateObject(user) 时,我执行了 2 个查询:
休眠:插入用户(创建,修改,电子邮件,名字,姓氏)值(?,?,?,?,?)休眠:插入用户登录(创建,修改,密码,user_id)值(?,?,?, ?) [2012-08-15 12:15:04,192] [错误] [http-bio-8080-exec-1] SqlExceptionHelper [144]: 列 'user_id' 不能为空
并且看起来两个对象之间没有引用。如果进入实体用户,方法 setUserLogin 我添加行 userLogin.setUser(this); 它的工作,但老实说,我不觉得这种方式优雅。我在实体配置中是否遗漏了什么可能不会自动执行的操作?
谢谢
这是我的实体
@Entity
@NamedQueries({ @NamedQuery(name = "user.list", query = "select u from User u") })
public class User implements java.io.Serializable {
@Column(name = "first_name", nullable = true)
private String firstName;
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name="user_id", nullable=false)
private UserLogin userLogin;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public UserLogin getUserLogin() {
return userLogin;
}
public void setUserLogin(UserLogin userLogin) {
this.userLogin = userLogin;
//userLogin.setUser(this); THIS IS THE LINE THAT FIXES IT, BUT I DONT FIND THIS WAY ELEGANT
}
}
@Entity
@Table(name="user_login")
public class UserLogin implements java.io.Serializable {
@Column(name = "password", nullable = false)
private String password;
@OneToOne(optional = false, fetch = FetchType.LAZY)
private User user;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
JSP 文件:
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<form:form action="/test" commandName="user">
<tr>
<td>User Name :</td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:input path="userLogin.password" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Register"></td>
</tr>
</table>
</form:form>
</body>
</html>
弹簧控制器:
@Controller(value = "/")
public class Test {
@Autowired
UserServiceImpl userServiceImpl;
@RequestMapping(method = RequestMethod.GET, value = "/test")
public void test(ModelMap model) {
model.addAttribute("user", new User());
}
@RequestMapping(method = RequestMethod.POST, value = "/test")
public void test(User user) {
userServiceImpl.update(user);
}
}