Manytomany "Project essay" about exception object references an unsaved transient instance

Source: Internet
Author: User

An exception occurred while saving Manytomany:

Org.springframework.dao.InvalidDataAccessApiUsageException:org.hibernate.TransientObjectException:object References an unsaved transient instance

Cause: One-way manytomany save in the reverse order, you should first save the main Terminal permission object

Error code:

@Transactional (readonly=false) @Lock (lockmodetype.optimistic_force_increment) @CacheEvict (value= "Permissionlist", allentries =true)     PublicPermission Save (Permission Permission) {Permission.setmenu (Menudao.findone (Permission.getmenuid ())); List<Role> roles =Roledao.findbydatascope (DataScope.ALL.getValue ());  for(Role temp:roles) {List<Permission> permissions =temp.getpermissions ();        Permissions.add (permission);        } roledao.save (roles);  Permission.setroles (roles); //permissions belong to this role        returnpermissiondao.save (permission); }

Two classes, role roles and Permissions permission, a role can have multiple permissions, and vice versa.

The code is as follows:

 Packagenet.myspring.blue.modules.sys.entity;Importjava.util.List;Importjavax.persistence.Cacheable;ImportJavax.persistence.Column;Importjavax.persistence.Entity;ImportJavax.persistence.JoinColumn;Importjavax.persistence.JoinTable;ImportJavax.persistence.ManyToMany;Importjavax.persistence.Table;Importjavax.persistence.Transient;Importcom.google.common.collect.Lists;Importnet.myspring.blue.common.persistence.DataEntity;Importnet.myspring.blue.common.utils.Collections3;/*** The persistent class for the Sys_role database table. **/@Entity @table (name= "Sys_role") @Cacheable Public classRoleextendsdataentity {PrivateString Code; PrivateInteger Datascope; PrivateString name; PrivateList<permission> permissions=lists.newarraylist (); PrivateList<user> users=lists.newarraylist (); PrivateList<long> permissionids=lists.newarraylist ();  PublicRole () {} PublicString GetCode () {return  This. Code; }     Public voidSetcode (String code) { This. Code =Code; } @Column (Name= "Data_scope")     PublicInteger Getdatascope () {return  This. Datascope; }     Public voidSetdatascope (Integer datascope) { This. Datascope =Datascope; }     PublicString GetName () {return  This. Name; }     Public voidsetName (String name) { This. Name =name; }    //bi-directional Many-to-many Association to Permission@ManyToMany @JoinTable (name= "Sys_role_permission", Joincolumns = {@JoinColumn (name = "role_id")}, Inversejoincolumns = {@JoinColumn (name = "Permi ssion_id ") })     PublicList<permission>getPermissions () {return  This. Permissions; }     Public voidSetPermissions (list<permission>permissions) {         This. Permissions =permissions; }    //bi-directional Many-to-many Association to User@ManyToMany (mappedby= "Roles")     PublicList<user>getusers () {return  This. Users; }     Public voidSetusers (list<user>users) {         This. Users =users; } @SuppressWarnings ("Unchecked") @Transient PublicList<long>Getpermissionids () {if(permissionids!=NULL&& permissionids.size () ==0 &&collections3.isnotempty (permissions)) {Permissionids= Collections3.extracttolist (permissions, "id"); }        returnPermissionids; }     Public voidSetpermissionids (list<long>permissionids) {         This. Permissionids =Permissionids; }}

Permission Permission class

 Packagenet.myspring.blue.modules.sys.entity;ImportJavax.persistence.*;ImportNet.myspring.blue.common.config.Global;Importnet.myspring.blue.common.persistence.DataEntity;Importnet.myspring.blue.common.utils.Collections3;Importcom.google.common.collect.Lists;Importjava.util.List;/*** The persistent class for the Sys_permission database table. **/@Entity @table (name= "Sys_permission") @Cacheable Public classPermissionextendsdataentity {PrivateString name; PrivateString permission; Privatemenu Menu; PrivateList<role> roles=lists.newarraylist (); PrivateLong menuId;  PublicPermission () {} PublicString GetName () {return  This. Name; }     Public voidsetName (String name) { This. Name =name; }     PublicString getpermission () {return  This. Permission; }     Public voidsetpermission (String permission) { This. Permission =permission; }    //bi-directional Many-to-one Association to Menu@ManyToOne (fetch=fetchtype.lazy) @JoinColumn (name= "menu_id")     PublicMenu GetMenu () {return  This. menu; }     Public voidSetMenu (Menu menu) { This. Menu =menu; }    //bi-directional Many-to-many Association to Role@ManyToMany (mappedby= "Permissions")     PublicList<role>GetRoles () {return  This. Roles; }     Public voidSetroles (list<role>roles) {         This. roles =roles; } @Transient PublicLong Getmenuid () {if(menuid==NULL&& menu!=NULL) {menuId=Menu.getid (); }        returnmenuId; }     Public voidSetmenuid (Long menuId) { This. MenuId =menuId; } @Transient PublicString getrolenames () {returncollections3.extracttostring (Roles, "name", Global.char_comma); }}

Note that the main control side is the permission class, and the Annotation "@ManyToMany (mappedby=" permissions ")" explains this

Business Scenario:

Admin role is to have "arbitrary permissions", I add new permissions, the permissions should be synchronized by the admin owned.

The list<role> of a role that corresponds to a permission should also be equal to a role with "arbitrary permissions" .->list<role> roles = Roledao.findbydatascope ( DataScope.ALL.getValue ());

Save, you must first save the host Terminal permission, or the database will be error

The correct wording

@Transactional (readonly=false) @Lock (lockmodetype.optimistic_force_increment) @CacheEvict (value= "Permissionlist", allentries =true)     PublicPermission Save (Permission Permission) {Permission.setmenu (Menudao.findone (Permission.getmenuid ())); List<Role> roles =Roledao.findbydatascope (DataScope.ALL.getValue ());        Permission.setroles (roles);  Permissiondao.save (permission); Note The order of Save permission first for(Role temp:roles) {List<Permission> permissions =temp.getpermissions ();        Permissions.add (permission);  } roledao.save (roles); After rolesreturn NULL; }

Manytomany "Project essay" about exception object references an unsaved transient instance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.