我有兩個表:UserExtended
繼承自User
。但我無法推廣現有的User
至UserExtended
。休眠繼承(TABLE_PER_CLASS)表擴展
實體:
@Entity
@Table
@Inheritance(strategy = InheritanceType.JOINED)
public class User {
// columns: id, email, etc.
}
@Entity
@Table
@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
public class UserExtended extends User {
// columns
}
服務:
// Repositories
@Autowired
private UserDao userDao;
@Autowired
private UserExtendedDao userExtendedDao;
public void promoteUser() {
User user = userDao.getUserByEmail(email);
UserExtended userExt;
if (user != null) {
if (user instanceof UserExtended) {
// cast UserExtended
userExt = (UserExtended) user;
} else {
// extend User to UserExtended
userExt = new UserExtended();
userExt.setId(user.getId());
// userExt.setEmail(user.getEmail());
userExt = userExtendedDao.save(userExt); // exception here!
}
} else {
// create new UserExtended
}
}
有了這個代碼,我得到異常:SQLServerException: Cannot insert the value NULL into column 'email', table 'User'; column does not allow nulls. INSERT fails
因爲email
列不爲空的DB。
當我取消對該行userExt.setEmail(user.getEmail());
我得到另一個異常SQLServerException: Cannot insert duplicate key row in object 'User' with unique index 'UQ_User_email'. The duplicate key value is ([email protected])
因爲email
應該是唯一的。
我可以用普通SQL做插入INSERT INTO UserExtended (id) VALUES (13);
我怎樣才能使用Hibernate和Spring Data JPA做同樣的事情?