[英]One-to-one mapping hibernate and not null
我是休眠的新手,也是MySQL的新手。 我有以下兩個表:
CREATE TABLE storeman.user (
id INT NOT NULL AUTO_INCREMENT,
email VARCHAR(80) NOT NULL,
display_name VARCHAR(50),
password CHAR(41),
active BOOLEAN NOT NULL DEFAULT FALSE,
provisional BOOLEAN NOT NULL DEFAULT FALSE,
last_login TIMESTAMP,
PRIMARY KEY (id),
UNIQUE INDEX (email)
);
CREATE TABLE storeman.user_preferences (
id INT NOT NULL AUTO_INCREMENT,
notify_login BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (id),
CONSTRAINT id_foreign FOREIGN KEY (id) REFERENCES user (id) ON DELETE CASCADE
);
在Eclipse中,我使用休眠工具生成了域代碼類。 User.java看起來像這樣(簡體):
@Entity
@Table(name = "user", catalog = "storeman", uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class User implements java.io.Serializable {
private Integer id;
[...]
private UserPreferences userPreferences;
public User() {
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
[...]
@OneToOne(fetch = FetchType.LAZY, mappedBy = "user")
public UserPreferences getUserPreferences() {
return this.userPreferences;
}
}
我的問題是與getUserPreferences
:當然,如果創建新用戶或從不存在user_detail
表中相應行的數據庫中讀取數據,則它將返回null
。 這是正確的,但是它迫使我在訪問其成員之前檢查userPreferences
是否不為null。 從編碼的角度來看,它並不是那么方便。 因此,我像這樣更改了User.getUserPreferences
方法,以獲取默認值:
@OneToOne(fetch = FetchType.LAZY, mappedBy = "user")
public UserPreferences getUserPreferences() {
if (this.userPreferences==null)
this.userPreferences = new UserPreferences();
return this.userPreferences;
}
這很好,但是,如果我需要使用休眠工具重新生成域代碼(User.java),則更改將丟失。 所以我的問題是:是否有一種方法(即使通過修改mySQL表/關系)也可以始終自動設置userPreferences?
使用某些配置或類似的方法,無法在代碼之外(至少我無法想到)執行此操作。
您可以做的一件事是在聲明關系時對其進行初始化
private UserPreferences userPreferences = new UserPreferences()
但這也將無法在代碼再生中幸存下來。 我能想到的唯一的另一種方法是將初始化代碼放入某種util方法中,這樣就可以在那里維護它,而不用考慮重新生成實體代碼。
UserUtils.getUserPreferences(User user)
但是,這僅適用於您編寫的代碼,如果某些框架需要它,您將再次獲得空值,因為它將不使用您的util方法(在這種情況下,第一種方法更好)。
請記住,當您在托管實體上初始化此對象時,新對象將保留在數據庫中。
User user = userDAO.getUser(id);
user.getUserPreferences(); // this code initializes the relation (new UserPreference())
在這些行之后,如果cascade
是以這種方式配置的,則將在user_preferences
表中獲得一行,否則,您將收到一個抱怨抱怨在試圖保留的實體中找到瞬態實體的異常。
說了這么多,難道真的很難檢查某些東西是否為空,特別是如果根據業務規則允許它為空?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.