JPA修改树结构的关联关系:
JAP默认是以主键和parent字段自动形成树结构,当添加children属性后,查询时自动会将父节点下的子节点组装到children属性中,
但是如果是非主键字段和parent字段形成树结构的话,需要手动去指定其关系eg:
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "parent_id",referencedColumnName = "id")
@JoinColumn(name = "station_code",referencedColumnName = "station_code")
private Set<myTree> children;
其中@JoinColumn注解用来指定与所操作实体相关联的数据库表中的列字段;
@OneToMany用来建立一对多的关系映射,用于指定与之关联的多个实体;
id为非主键字段,并且不同的station_code对应的id会重复,所以又添加了station_code关联字段。
package com.cars.ict.rbpsems.entity.controlpisled;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Set;
@Entity
@Table(name = "my_tree")
@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler", "fieldHandler"})
public class myTree implements Serializable {
@Id
@Column(length = 50, name = "ids")
private String ids;
//id不再为主键
@Column(length = 50, name = "id")
private String id;
@Column(length = 50, name = "rela_tree_id")
private String relaTreeId;
/**
* 上級
*/
// @JsonIgnore
// @ManyToOne(fetch = FetchType.LAZY)
@Column(name = "parent_id")
private String parent;
----------------------------旧的写法--------------------------------
//@OneToMany(fetch = FetchType.EAGER, mappedBy = "parent")
//@OrderBy(value = "code asc")
//private Set<StationRegionTree> children;
---------------------------------------------------------------------
//==========================绑定新的关系,以id和station_code为关联条件=================
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "parent_id",referencedColumnName = "id")
@JoinColumn(name = "station_code",referencedColumnName = "station_code")
//@OrderBy(value = "code asc")
private Set<myTree> children;
//======================================================================================
/**
* 基础信息值
*/
@Column(length = 20, name = "inf_value")
private String infValue;
/**
* 基础信息编码(简称)
*/
@Column(length = 500, name = "inf_code")
private String infCode;
/**
* 基础信息类型
*/
@Column(length = 2, name = "inf_type")
private String infType;
/**
* 基础信息名称
*/
@Column(length = 20, name = "inf_name")
private String infName;
/**
* 名称
*/
@Column(length = 20, name = "station_name")
private String stationName;
/**
* 基础信息标示
*/
@Column(length = 100, name = "inf_mark")
private String infMark;
/**
* 信息状态
*/
@Column(length = 1, name = "rela_tree_state")
private String relaTreeState;
/**
* 车编码
*/
@Column(length = 20, name = "station_code")
private String stationCode;
/**
* 区域是否被监控管理
*/
@Column(name = "s_ismonitored")
private String ismonitored;