【发布时间】:2012-09-02 08:28:45
【问题描述】:
我想用共享主键创建双向的一对一关系。
正如这里所说的JPA Hibernate One-to-One relationship 我有:
@Entity
public class UserProfileInformation {
@Id
@GeneratedValue(generator = "customForeignGenerator")
@org.hibernate.annotations.GenericGenerator(
name = "customForeignGenerator",
strategy = "foreign",
parameters = @Parameter(name = "property", value = "userEntity")
)
long id;
private long itemsPerPage;
@OneToOne(mappedBy="userProfileInformation")
private UserEntity userEntity;
...}
@Entity
@Table(name = "UserTable")
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String publicName;
private String password;
private String emailAddress;
private String name;
private boolean active;
@OneToOne(cascade=CascadeType.ALL)
@PrimaryKeyJoinColumn
private UserProfileInformation userProfileInformation;
...}
现在,当我尝试将我的用户保存在数据库中时,我得到了org.hibernate.id.IdentifierGenerationException: null id generated for:class pl.meble.taboret.model.UserProfileInformation。是因为,当 userProfileInformation 被持久化到数据库 userEntity 时没有生成 id 吗?
另外,在我的示例中,如何创建与共享主键的双向关系?
编辑: 请求代码,这是一个简单的控制器来测试持久化用户实体的操作。
@Controller
@RequestMapping("/test")
public class TestController {
@Autowired
UserDao userDao;
@RequestMapping(method= RequestMethod.GET)
public String t(Model model){
UserEntity entity=new UserEntity();
entity.setActive(false);
entity.setEmailAddress("a");
entity.setName("name");
entity.setPassword("qqq");
entity.setPublicName("p");
UserProfileInformation p = new UserProfileInformation(entity);
entity.setUserProfileInformation(p);
userDao.addUser(entity);
return "login";
}
}
【问题讨论】:
-
显示您在其中创建/保存 UserProfileInformation 实体的代码。您是否正确设置了 userEntity 引用?还要检查将类型从 long 更改为 Long 是否有效。
-
我将代码添加到已编辑的第一篇文章中,此外,将类型从 long 更改为 Long 并没有解决问题。
-
看看这个 - stackoverflow.com/questions/4027623/…。我认为这与哪一方是拥有方有关-您可能需要交换 mappedBy 和 PrimaryKeyJoinColumn
-
我读了这篇文章,但问题是,mapped by 指向标记关联的非拥有方。对我来说很奇怪,我应该在 UserEntity 端使用 mapped by,这是 imo 的拥有端。可以这么说,我就是无法理解这一点。
标签: java hibernate sqlite jpa jpa-2.0