2014-11-06 75 views
2

考慮以下情形:休眠 - 生成的SQL包含多個字段比我更新

class User { 
    Long id; 
    BigDecimal balance; 
    BigDecimal rating; 

    @ManyToOne 
    Team team; 
} 

class Team { 
    Long id; 
    BigDecimal rating; 
} 

然後在代碼中,我有以下幾點:

@Transactional 
void updateBalance(...) { 
    user.addBalance(balance);     // add balance 
    increaseUserRating(user, balance);   // update rating by an algorithm 
    increaseTeamRating(user.getTeam(), balance);// update team rating by an algorithm 
} 

所以,我希望要執行下面的SQL :

update users set balance = $1, rating = $2 where id = $3; 
-- update teams as well 

,但我得到:

update users set balance = $1, rating = $2, team_id = $3; -- why's the team updated huh? 

這是正常行爲嗎?我懷疑team_id已更新,以保證數據的一致性,因爲我們也更新了團隊。我對麼?

+0

@ M.Deinum,請參閱更新。 '登錄'字段不變。 – 2014-11-06 08:11:51

+0

這個團隊很髒,所以得到一個更新(你正在做一些提高團隊評級的東西),然後hibernate認爲,由於骯髒的團隊,它也需要更新該領域。有趣的順便說一句,在歷史上更新的所有領域(但可能已與JPA更改,不知道)。 – 2014-11-06 08:16:18

+0

這些是完整的SQL語句嗎?沒有WHERE子句? – 2014-11-06 08:29:24

回答

0

當您嘗試更改與某個其他域的關係的域的任何值時,如您的案例 Many Users to a Team Unidirectional with User as the Relation Holder。這裏您將有Team as an object for every User domain因此,當您更新用戶對象時,它將嘗試更新域的每個字段User,因此它也會嘗試更新與用戶關聯的對象Team

此外,如果您嘗試更新Team對象,則不會更新用戶對象。