我想创建具有共享主键的双向一对一关系。
正如此处所述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 ,用于测试持久化 UserEntity 的操作。
@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";
}
}
最佳答案
我认为问题出在 id 生成策略上。对于 hibernate,@GenerateValue(strategy = GenerationType.AUTO)
转换为 native
标识符生成。这意味着 hibernate 需要 UserTable 的 identity
id 字段。
我不知道 SQLite
在标识列方面到底是如何工作的,但似乎来自 this SO question有点不同(参见第二个答案)。
无论如何,如果您计划在多个数据库上运行应用程序,为了可移植性更好,可以从 GenerationType.AUTO
更改 id 生成策略并使用 hibernate 增强型生成器:SequenceStyleGenerator
或 TableGenerator
。请参阅this link在 hibernate 文档中。
编辑:
我尝试重现您的问题,但似乎 SQLite 方言不在官方支持范围内 hibernate dialects 。同时我用 H2 embeded database 测试了你的情况。它按预期工作:您的映射是正确的。
如果您使用非官方 SQLite 方言,则该方言可能存在错误。
关于java - JPA/Hibernate - 共享主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12335317/