当前位置:网站首页>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
边栏推荐
- 剑指Offer刷题记录——Offer 05. 替换空格
- How to record enterprise or personal domain names
- 快速理解重定向
- Xiaodi network security - Notes (3)
- Pytorch learning notes (I)
- 9.账户和权限
- Paper reading: deep residual learning in spiking neural networks
- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
- 字典,集合的使用,数据类型的转换
- M BTS antenna design based on MATLAB, with GUI interface
猜你喜欢
随机推荐
剑指Offer刷题记录——Offer 05. 替换空格
天翼雲 杭州 雲主機(VPS) 性能評測
Steam游戏服务器配置选择 IP
Sword finger offer question brushing record - offer 07 Rebuild binary tree
m3GPP-LTE通信网络中认知家庭网络Cognitive-femtocell性能matlab仿真
What if the website is hijacked?
Performance evaluation and comparison of Huawei cloud Kunpeng arm ECs and x86 ECS
华为云 鲲鹏ARM云服务器 和 x86云服务器 性能评测对比
爬虫基础—代理的基本原理
TypeScript(ts-loader,tsconfig.json及lodash)
What role does 5g era server play in this?
Minecraft bedrock BDS service tutorial
Speed feedback single closed loop DC speed regulation system based on Simulink
IP103.53.125.xxx IP地址段 详解
M BTS antenna design based on MATLAB, with GUI interface
快速掌握sort命令,tr命令
Data analysis and visualization -- the shoes with the highest sales volume on jd.com
Weight matching (greedy)
基于simulink的转速反馈单闭环直流调速系统
Performance evaluation and comparison of lightweight application servers of major cloud service manufacturers, Alibaba cloud, Tencent cloud, Huawei cloud, and ucloud







