自我映射一对多冬眠春季靴

时间:2019-05-16 10:41:46

标签: java hibernate spring-boot junit hibernate-mapping

MYSQL架构:

CREATE TABLE `nodes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `node_id` int(11) DEFAULT NULL,
  `name` varchar(255) NOT NULL,
  `type` int(255),
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `node_id_self_to_id` (`node_id`),
  KEY `type_foreign_to_node_types` (`type`),
  CONSTRAINT `node_id_self_to_id` FOREIGN KEY (`node_id`) REFERENCES `nodes` (`id`),
  CONSTRAINT `type_foreign_to_node_types` FOREIGN KEY (`type`) REFERENCES `node_types` (`id`)
)

我的实体类:

@Entity
@Table(name = "nodes")
public class Nodes {
@Id
@JoinColumn(name = "node_id")
private int id;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="node_id")
private Nodes nodeId;

@OneToMany(mappedBy="nodeId")
private Set<Nodes> mynodeIds = new HashSet<Nodes>();

private String name;
private Date created_at;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "type")
private Nodetypes nodetypes;

@OneToMany(mappedBy = "nodes", cascade = CascadeType.ALL)
private Set<Nodeattributes> nodeattributes;

@OneToMany(mappedBy = "nodes", cascade = CascadeType.ALL)
private Set<Products> products;


public Nodetypes getNodetypes() {
    return nodetypes;
}

public void setNodetypes(Nodetypes nodetypes) {
    this.nodetypes = nodetypes;
}

public Set<Products> getProducts() {
    return products;
}

public void setProducts(Set<Products> products) {
    this.products = products;
}

public Set<Nodeattributes> getNodeattributes() {
    return nodeattributes;
}

public void setNodeattributes(Set<Nodeattributes> nodeattributes) {
    this.nodeattributes = nodeattributes;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Date getCreated_at() {
    return created_at;
}

public void setCreated_at(Date created_at) {
    this.created_at = created_at;
}
}

在Junit测试中,

public void testCreateNodes() {
    Nodes node1 = new Nodes();
    node1.setId(2222);
    node1.setCreated_at(new java.util.Date());
    node1.setName("nodeName");
    node1.setNodetypes(nodetypesRepository.findById(1111).get());
    nodesRepository.save(node1);
}

我正在使用Spring Boot Project。如何在Hibernate中进行一对多的自我映射。因此,我该如何一对多地实现休眠自连接注释?任何帮助,将不胜感激。我已经跟随该博客来开发该项目,但是在我的MYSQL中仍然获得空值。

https://viralpatel.net/blogs/hibernate-self-join-annotations-one-to-many-mapping/

0 个答案:

没有答案