Hibernate many-to-many relationship configuration and lazy loading essays

1. How to configure the many-to-many relationship

  有三张表 role、permission,分别是角色与权限表,二者是多对多关系,对应关系的中间表为p_role_permission,中间表中r_sysId对应role表中的主键sysId、中间表中p_sysId列对应permission表中的主键sysId(说白了就是中间表中两列是外键列分别指向role和permission表)。下面代码是role表对应的注解配置实体类


@Entity
@Table(name="role",catalog="byky")
     pubic class Role{
        	......
        	@ManyToMany(fetch=FetchType.LAZY)
        	@JoinTable(name="p_role_permission",joinColumns=     {@JoinColumn(name="r_sysId",referencedColumnName = "sysId")},inverseJoinColumns={@JoinColumn(name="p_sysId",referencedColumnName = "sysId")})
        	  public Set<Permission> getPermissions() {
        			return permissions;
        	  }
        	......
        } 
  • The fetch value in the @ManyToMany annotation can be configured with two options: fetch=FetchType.LAZY means lazy loading, using proxy technology, when the role object is loaded, the permissions attribute of the role object will not be loaded temporarily, when the getPermissions() of the role is called, hibernate will take it. Query the database to load the data. One point needs to be particularly emphasized. Lazy loading requires the session of hibernate to be open. The session associated with the current role object is closed. When calling the permissions property of the role object, an error com.sun.jdi.InvocationException will be reported. So be careful not to get the delayed-loading attribute value after the session is closed. It is common to call it in Contreller, unless you use declarative things to delay the closing of the getCurrentSession method.
  • @ManyToMany annotation in the fetch value configuration fetch=FetchType.EAGER means to load immediately, it will not be able to read the data when the session is closed, but will cause data query redundancy, useless attributes are read out all at once, causing pressure on the database .
  • The name="p_role_permission" in @JoinTable configures the name of the intermediate table, joinColumns= {@JoinColumn(name="r_sysId",referencedColumnName = "sysId")} in @JoinColumn(name="r_sysId" configures the current class correspondence The foreign key field of the table in the intermediate table, referencedColumnName = "sysId" configures the primary key field corresponding to the foreign key of the intermediate table in the current class;
    inverseJoinColumns={@JoinColumn(name="p_sysId",referencedColumnName = "sysId")} Yes Refers to another table permission corresponding to the current class many-to-many, the first @JoinColumn (name="p_sysId" is also the foreign key field corresponding to the permission table in the intermediate table, referencedColumnName = "sysId") only the permission and the intermediate table The primary key field sysId corresponding to the foreign key p_sysId field.
  • The cascade cascade operation is more important, so we will put a title to explain it separately.

2. Cascade cascade operation

Hibernate's cascade operation is for objects and objects. This can be seen from the configurable items of cascade. Don't confuse it with the cascade operation in the database when considering.
Two cascade configurations:

Configure on the annotations of @OneToOne, @OneToMany, @ManyToOne, @ManyToMany, using javax.persistence.CascadeType, which is the JPA configuration

 @ManyToMany(fetch=FetchType.LAZY,casecade={CasecadeType.DETACH,CascadeType.MERGE})

The content of casecade is an array of CasecadeType. Multiple content can be configured, if there is only one configuration item, it can be directly written as casecade=CasecadeType.DETACH, the form in the code is like this

@ManyToMany(fetch=FetchType.LAZY,casecade=CascadeType.MERGE)

Another configuration method is to use org.hibernate.annotations.CascadeType, that is, the hibernate annotation configuration form is as follows

@ManyToMany(fetch=FetchType.LAZY)
@Cascade(value={ org.hibernate.annotations.CascadeType.DETACH})
@JoinTable(name="p_role_permission",joinColumns={@JoinColumn(name="r_sysId",referencedColumnName = "sysId")},inverseJoinColumns={@JoinColumn(name="p_sysId",referencedColumnName = "sysId")})
public Set<PPermission> getPermissions() {
	return permissions;
}

It can be seen that the @Casecade annotation is used, where the value value is an array of type org.hibernate.annotations.CascadeType, which can be configured with multiple values ​​or set a value.
Casecade function: whether to cascade the objects in the annotated field. Optional values when using JPA settings : javax.persistence.CascadeType.PERSIST, MERGE, REMOVE, REFRESH, DETACH, ALL. One or more of them can be selected. When choosing one, the curly braces can be used or not

Optional value Description
PERSIST The persist operation of the cascaded session. Assuming that the @ManyToMany annotation of the Student class and the teachers field is configured with cascade = {CascadeType.PERSIST}, then, when the stu1 object sets a teachers collection (the objects in this collection are transient), when the stu1d object is persisted , All transient objects in this collection will be cascaded and persisted to the database.
MERGE Cascade merge operation. Same as above
REFRESH Cascade refresh operation. Same as above
REMOVE Cascade remove operation. Same as above
DETACH Cascade evict operation. Same as above
ALL Cascade all the above operations
The first five selection values ​​above are respectively associated with the method in the session, and only the corresponding method can trigger

If you use the CascadeType annotated by Hibernate itself, the optional values ​​are as follows:

Optional value Description
DELETE The delete method in cascaded session
DELETE_ORPHAN Obsolete and not recommended
DETACH Equivalent to JPA's CascadeType.DETACH
EVICT Obsolete, please use the previous DETACH
MERGE Equivalent to CascadeType.MERGE
PERSIST Equivalent to CascadeType.PERSIST
REFRESH Equivalent to CascadeType.REFRESH
REMOVE Equivalent to CascadeType.REMOVE.
REPLICATE REPLICATE method in cascaded session
SAVE_UPDATE Three methods of cascading session.save() or session.update() or session.saveOrUpdate()
ALL Cascade all the above operations

Note that improper use of cascade operation will affect performance

Guess you like

Origin blog.csdn.net/u011930054/article/details/87690287