[英]JPA / Hibernate unidirectional one-to-one mapping with shared primary key
[英]JPA/Hibernate - shared primary key
我想使用共享主鍵創建雙向一對一關系。
如此處所述,我擁有JPA休眠一對一關系 :
@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?
另外,在我的示例中我該怎么做以共享主鍵創建雙向關系?
編輯:要求的代碼,這是測試持久化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生成策略。 對於休眠,@ @GeneratedValue(strategy = GenerationType.AUTO)
轉換為native
標識符生成。 這意味着休眠狀態需要UserTable的identity
ID字段。
我SQLite
知道SQLite
在身份列方面的工作方式,但是從這個SO問題看來似乎有些不同(請參閱第二個答案)。
無論如何,如果您打算在多個數據庫上運行應用程序,則可移植性更好,可以從GenerationType.AUTO
更改ID生成策略,並使用休眠增強型生成器: SequenceStyleGenerator
或TableGenerator
。 請參閱休眠文檔中的此鏈接 。
編輯:
我試圖重現您的問題,而且SQLite方言似乎不在官方支持的休眠方言之列 。 同時,我使用H2嵌入式數據庫測試了您的案例,它可以按預期工作:您的映射正確。
如果您使用的是非官方的SQLite方言,則該方言可能是一個錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.