我要試着解釋我的問題以及我可以 我有一些用戶組來管理用戶權限。問題更新編號
某些用戶可能是客戶。用戶表和客戶表之間有一個OneToOne連接。以及用戶和組之間的OneToOne連接。當我刪除一個客戶端時,我希望用戶組從用戶到用戶都是默認組(Id = 4)。
有了這個代碼:
public static void delete(Long id) {
Customer entity = Customer.findById(id);
User entityUser = User.findById(entity.user.id);
entity.delete();
entityUser.groups.id = (long)4;
entityUser.merge();
entityUser.save();
flash.success(Messages.get("Users.deleted"));
Customers.list();
}
組型號:
@Entity
@Table(name = "groups")
public class Group extends Model{
@Required
public String name;
@Required
public String description;
public Group(String name, String description)
{
this.name = name;
this.description = description;
}
用戶模式:
@Entity
@Table(name = "users")
public class User extends Model{
@Required
public String firstname;
@Required
public String lastname;
@As("dd/MM/yyyy")
@Required
public Date birthday;
@Required
public String avatar;
@Required
public String adress;
@Required
public String phonenumber;
@Required
@Email
public String email;
@Required
public String username;
@Required
@Password
public String password;
@OneToOne
@Required
public Group groups;
public User(
String firstname,
String lastname,
@As("dd/MM/yyyy") Date birthday,
String avatar,
String adress,
String phonenumber,
String email,
String username,
String password,
Group groups
)
{
if(groups == null){
groups.id = (long)4;
}
else
{
this.groups = groups;
}
this.firstname = firstname;
this.lastname = lastname;
this.birthday = birthday;
this.avatar = avatar;
this.adress = adress;
this.phonenumber = phonenumber;
this.email = email;
this.username = username;
this.password = password;
}
客戶模式:
@Entity
@Table(name = "customers")
public class Customer extends Model{
@As("dd/MM/yyyy")
public Date dateinscription;
public Double amountdue;
public Double amountpaid;
@Required
public String picture;
@OneToOne
public User user;
public Customer(@As("dd/MM/yyyy") Date dateinscription, Double amountdue, Doubleamountpaid, String picture, User user)
{
this.dateinscription = dateinscription;
this.amountdue = amountdue;
this.amountpaid = amountpaid;
this.picture = picture;
this.user = user;
}
}
但我得到了一個錯誤:
PersistenceException occured : org.hibernate.HibernateException: identifier of an instance of models.Group was altered from 3 to 4
在/app/controllers/Customers.java(約69行) 65:
66: entityUser.groups.id =(長) 4; 67:
68: entityUser.merge(); 69: entityUser.save(); 70:
71: flash.success(Messages.get(「Users.deleted」)); 72: Customers.list(); 73:
74: } 75:
我試着用GenericModel,但沒有奏效。
請幫助我!
謝謝。
非常感謝你這是很好的解決方案:) – GJean
我還建議,而不是使用整數作爲一個神奇的數字在那裏,您創建一個常數,所以你召喚出更明確的,爲什麼這是「4」。在這種情況下,我通常會通過不會更改的特定字段(例如findByName(「Default」))來查找實體,以防萬一最終部署中的id與開發中的id不同。 –