当前位置:网站首页>Nanny level one-stop service - self correlation to construct parent-child relationship (@jsonbackreference and @jsonmanagedreference solve circular dependency)
Nanny level one-stop service - self correlation to construct parent-child relationship (@jsonbackreference and @jsonmanagedreference solve circular dependency)
2022-07-19 07:13:00 【Cainiaoji】
Nonsense
I, an unknown rookie, would be urged to be more ( It's already may , I haven't fulfilled my promise 🥴 But I remember , Because I was flattered ). So next, I decided to explode my liver for seven days and seven nights to publish a few of his boutiques ( Draw a big cake first )
Finally, it's not a series of articles on rookie learning , But I'm still that rookie , Nothing has changed , The only change is the gradual reduction of hair volume .
Writing code a few days ago was hit , The menu classification function I wrote in two days was re implemented by a colleague in the group in two hours , Look at other people's code is really beautiful , Look at me again , A piece of shit .
Half a year to see , A little more nonsense . Next, I will attach some explanations to this beautiful code to share with you ( My shit code doesn't show up here )
Text
In business, it is inevitable to encounter some demand for hierarchical display of goods or menus , These menu management involves classification . Now I'll show you how to implement it according to the process ( Because I'm a rookie too , So I know that you may not be very familiar with some annotations involved in the code , So I will explain one by one later , After understanding the code, you can safely and boldly use CtrlCV Skills. !)
Construct classification entities
After the entity is constructed, the parent-child structure relationship of classification and classification is realized , In the future, we can expand new implementations according to business needs .
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Builder
@Getter
@Table(name = "tb_category")
@GenericGenerator(name = "category-uuid", strategy = "uuid")
public class Category extends BaseEntity {
@Id
@GeneratedValue(generator = "category-uuid")
private String categoryId;
private String categoryName;
// Make a self-correlation , Realize the parent-child relationship
@JsonBackReference
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "parent_id", foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT))
@Getter
@Setter
@NotFound(action= NotFoundAction.IGNORE)
private Category parent;
@JsonManagedReference
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Category> childNodes;
@JsonProperty("parentId")
public String getParentId() {
if (this.parent == null) return "";
return this.parent.getCategoryId();
}
@JsonProperty("creationDate")
public Long getCreationTime() {
if(this.getCreationDate()==null) return 0L;
return this.getCreationDate().getTime();
}
@JsonProperty("lastUpdatedDate")
public Long getLastUpdatedTime() {
if(this.getLastUpdatedDate()==null) return 0L;
return this.getLastUpdatedDate().getTime();
}
@Setter
private Integer categoryLevel = 1;
private String categoryDescription;
private String categoryIconName;
private Integer status;
public static final String CATEGORY_VALID = "valid";
public static final String CATEGORY_ID = "categoryId";
// Add parent
public void addParentCategory(Category parentCategory) {
setParent(parentCategory);
setCategoryLevel(parentCategory.getCategoryLevel() + 1);
parentCategory.addChildren(this);
}
// Add child nodes
public void addChildren(Category child) {
if (this.childNodes == null) {
this.childNodes = Lists.newArrayList();
}
this.childNodes.add(child);
}
public boolean hasChildren() {
return getChildNodes().size() > 0;
}
// Get the child node down ( Don't include yourself )
public List<Category> getChildNodes() {
if (this.childNodes == null) return Lists.newArrayList();
return Collections.unmodifiableList(this.childNodes.stream().filter(x -> x.getValid() != 0).collect(Collectors.toList()));
}
// Get the child node down id( Don't include yourself )
@JsonIgnore
public List<String> getChildIds() {
if (this.childNodes == null) return Lists.newArrayList();
return Collections.unmodifiableList(this.childNodes.stream().filter(x -> x.getValid() != 0).map(Category::getCategoryId).collect(Collectors.toList()));
}
}
Here are some ways to implement common requirements :
// Get the current node and all parent nodes
public List<Category> findCategoryAndAllParents(List<Category> categories, Category category) {
// First add the current node to the collection
categories.add(category);
if (StringUtils.isNotEmpty(category.getParentId())) {
Category parent = getCategoryById(category.getParentId());
// Recursively look up the parent node
findCategoryAndAllParents(categories, parent);
}
categories.sort(Comparator.comparing(Category::getCategoryLevel));
return categories;
}
// Get current node id And all subset nodes id
public List<String> getChildrensAndSelfIds(String categoryId) {
Category category = getCategoryById(categoryId);
List<String> ids = new ArrayList<>();
// First add yourself to the set
ids.add(category.getCategoryId());
return getSelfIdAndAllChildIds(ids, category);
}
private List<String> getSelfIdAndAllChildIds(List<String> ids,Category category){
// All child nodes of the current node id Join the group
ids.addAll(category.getChildIds());
// Traverse to find the child nodes of the current node , Recursively put their child nodes id Join the group
category.getChildNodes().forEach(x->{
getSelfIdAndAllChildIds(ids,x);
});
return ids;
}
Explanation of notes
@JsonBackReference:Annotation used to indicate that associated property is part of two-way linkage between fields; and that its role is “child” (or “back”) link. Value type of the property must be a bean: it can not be a Collection, Map, Array or enumeration.
official API The document is described above , His general meaning is : This annotation is used to declare the relationship between two attributes with two-way connection .
@JsonBackReferenceThe function of annotation is “ Son ” link .( That is, the annotation Defined in child roles , Here is a little chestnut ), He must be marked on a bean On , And it cannot be a container such as a collection .Linkage is handled such that the property annotated with this annotation is not serialized; and during deserialization, its value is set to instance that has the “managed” (forward) link.( This paragraph will be later
@JsonBackReference and @JsonManagedReference The difference betweenUnified interpretation in )
@JsonManagedReference:Annotation used to indicate that annotated property is part of two-way linkage between fields; and that its role is “parent” (or “forward”) link. Value type (class) of property must have a single compatible property annotated with
JsonBackReference.@JsonManagedReferenceThe function of annotation is “ Father ” link .( That is, the annotation is defined in the parent role , Here is a little chestnut ) The value type corresponding to this attribute must be marked@JsonBackReferenceannotationLinkage is handled such that the property annotated with this annotation is handled normally (serialized normally, no special handling for deserialization); it is the matching back reference that requires special handling( This paragraph will be later
@JsonBackReference and @JsonManagedReference The difference betweenUnified interpretation in )
To make it easier to understand
@JsonBackReferenceand@JsonManagedReferenceannotation , Here is a simple example to use these two annotations ( The parent-child relationship I constructed above is self related )// This is a Teachers and students One to many example ( A teacher has many students , More than one student corresponds to one teacher . Equivalent to the teacher is the father , Students are children ) public class Teacher { private String name; private Integer age; @JsonManagedReference // Defined in the parent role private List<Student> students; } public class Student { private String name; private Integer age; @JsonBackReference // Defined in child roles , Marked on the parent attribute private Teacher teacher; }
@JsonBackReference and @JsonManagedReference The difference between
Jackson When serializing objects , If there is circular dependency in the object ( That is, the interdependence between teachers and students above ), It will report stack overflow . Use
@JsonBackReferenceand@JsonManagedReferenceIt is mainly to solve the circular dependency problem of one to many and many to one relationships . This pair of annotations is a powerful tool to solve the circular dependency between father and son .
From the official API As you can see in the document
@JsonBackReferenceThe properties of the annotation , Serialization in progress ( Convert the object to json data ) Will be ignored when ( That is... In the result json The data does not contain the content of this attribute ).@JsonManagedReferenceThe attributes of the annotation are serialized .Only when
@JsonBackReferenceand@JsonManagedReferencePut it together , When deserializing ,@JsonBackReferenceThe attribute value of the annotation can be automatically injected .
@JsonIgnore: Ignore an attribute directly , To break infinite recursion , Serialization or deserialization are ignored .@ManyToOne: Indicates that the current entity is a one to many relationship many One end .@JoinColumn: Configure foreign key- name: Foreign key field name , It is used to identify the name of the corresponding field in the table
@OneToMany: Indicates that the current entity is a one to many relationship One One end .mappedBy: Relationship maintenance
- mappedBy= “parent” It means that Category Class parent Attributes to maintain relationships , This name must be the same as Category Medium parent The attribute names are exactly the same
- OneToMany Must write mappedBy, One to many and many to one relationships may also generate a useless intermediate table to associate the two . However, we generally do not recommend the use of intermediate tables . Use mapperBy It can prevent the system from generating intermediate tables ( A field record foreign key will be added to the multi party database )
cascade: Cascade operation
- CascadeType. PERSIST Cascading persistence ( preservation ) operation
- CascadeType. MERGE update cascade ( Merge ) operation
- CascadeType. REFRESH Cascade refresh operation , Only query and get operations
- CascadeType. REMOVE Cascade delete operation
- CascadeType. ALL Cascade all the above operations
fetch: Load type , By default, load immediately , The more one is delayed loading
- FetchType.LAZY Lazy loading
- FetchType.EAGER Immediately load ( The default value )
@JsonInclude: This annotation is only useful for serialization operations , For control methods 、 Whether properties, etc. should be serialized- ALWAYS: The default policy , Serialization is performed in any case
- NON_NULL: Non empty
- NON_EMPTY:null、 Set array, etc. have no content 、 Empty string, etc , Will not be serialized
- NON_DEFAULT: If the field is the default value , It won't be serialized
@JsonProperty: Used on properties or methods , Serialize the name of the property into another name@NotFound: Ignore when the referenced foreign key data is not foundstay
many-to-one,one-to-one, In relationship , One party introduces the attributes of the other party , If the reference attribute value data is not found in the database ,hibernate Exceptions are thrown by default , Solve this problem , Add@NotFoundAnnotations can be
Partial reference :
https://www.jianshu.com/p/e85c3dfba052https://www.cnblogs.com/bolingcavalry/p/14360209.html
https://blog.csdn.net/qq_35357001/article/details/55505659
https://fasterxml.github.io/jackson-annotations/javadoc/2.6/com/fasterxml/jackson/annotation/JsonBackReference.html
http://www.manongjc.com/detail/24-riyzfvvluwotkdq.html
https://www.jianshu.com/p/27d9a42203be
边栏推荐
- Minecraft整合包 [GTNH]格雷科技:新视野 服务器搭建教程
- m基于simulink的16QAM和2DPSK通信链路仿真,并通过matlab调用simulink模型得到误码率曲线
- 传奇游戏架设教程
- Debug wechat one hop under linxu (Fedora 27)
- 函数与随机数
- Review summary of MySQL
- SYN洪水攻击的原理,syn洪水攻击的解决办法
- M FPGA implementation of chaotic digital secure communication system based on Lorenz chaotic self synchronization, Verilog programming implementation, with MATLAB chaotic program
- The principle of SYN Flood attack and the solution of SYN Flood Attack
- Quickly learn to use cut command and uniq command
猜你喜欢

wcdma软切换性能matlab仿真m,对比平均激活集数(MASN)、激活集更新率(ASUR)及呼叫中断概率(OP)三个性能指标

M simulation of 16QAM and 2DPSK communication links based on Simulink, and get the bit error rate curve by calling Simulink model through MATLAB
![[ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :](/img/dd/054af819c8bdca31bd135495386fb4.png)
[ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :

Évaluation des performances de la machine virtuelle Tianyi Cloud Hangzhou (VPS)

My world 1.12.2 Magic Baby (Fairy treasure dream) service opening tutorial

Solve the problem that the unit test coverage of sonar will be 0

Speed feedback single closed loop DC speed regulation system based on Simulink

搭建一个网站都需要那些东西

Minecraft Paper 1.18.1 版开服教程,我的世界开服教程,MCSManager9面板使用教程

Paper reading: deep residual shrink networks for fault diagnosis
随机推荐
linux下执行shell脚本调用sql文件,传输到远程服务器
Speed feedback single closed loop DC speed regulation system based on Simulink
Mapping rule configuration of zuul route
urllib库的使用
Review summary of MySQL
About file upload and download
基于simulink的转速反馈单闭环直流调速系统
103.53.124. What is the difference between X IP BGP line and ordinary dedicated line
M simulation of UWB MIMO radar target detection based on MATLAB, considering time reversal
How does legend open its service? What do you need to prepare to open legend private server?
快速理解重定向
Pycharm安装教程
Xiaodi network security - Notes (2)
Steam游戏服务器配置选择 IP
How do you know whether the network needs to use advanced anti DDoS server? How to choose the computer room is also very important, as well as the stability of the later business
1. What is a server?
STEAM游戏高主频i9-12900k 搭建CS:GO服务器
SNN学习日记——安装SpikingJelly
传奇怎么开服?开传奇私服需要准备什么呢?
剑指Offer刷题记录——Offer 04. 二维数组中的查找