1

I would like to store hierarchical folders in database. F.e

@Entity
public class Folder {

int id
String name
Folder parentFolder

}

So if folder is in subfolder he should store information about parentFolder If Folder is in root/top folder, it dosnt have any parentFolder, so there will be null

How should I set hibernate using annotation to achive this?

My entity class:

@Entity
@Table(name="common__Role")
public class Role {

/** The id. */
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;

/**
 * Parent Role id.
 */
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ROLE_ID")
public Role role;

/** The name. */
@Constraints.Required
public String name;
1
  • That is a @OneToMany nd a @ManyToOnerelation so you should handle this as such. Commented Oct 2, 2014 at 8:32

1 Answer 1

2

This should be your Entity ..

@Entity
@Table("FOLDER")
public class Folder {

  @Id
  private long id;

  @Column(name="NAME")
  private String name;

  @ManyToOne(fetch=FetchType.LAZY,cascade = {CascadeType.PERSIST,CascadeType.MERGE })
  @JoinColumn(name="PARENT_ID")
  private Folder parentFolder;


  //Getter and Setter
}

Maybe you should follow this tutorial

How to persist ManyToOne

Folder f= new Folder();
f.setName("name");

Folder fParent = entityManager.find(Folder .class, 1L);
f.setParent(fParent);

entityManager.persist(f);

See also this tutorial

Sign up to request clarification or add additional context in comments.

6 Comments

I've tried, but Your solution didnt resolve problem. When I add another Folder, and I am choosing parentFolder there is no error. But there is no relation id in database between child-parent
To save a relationship is needed a JoinColumn else does not work. You should add a column PARENT_ID. I suggest you a simple ManyToOne relationship using JPA.
" You should add a column PARENT_ID" - did You mean database? I've done this, but there goes only nulls. There is no relation
If you want persist everything you should add a cascade on relationship for the action that you needed. E.G. @ManyToOne(fetch=FetchType.LAZY,cascade = {CascadeType.PERSIST,CascadeType.MERGE })
It didnt helped. Remember that I have relation inside one entity
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.