Tony
Tony

Reputation: 3805

Specific kind of relation in hibernate

For example, I've got a table A with structure:

int id | int ref_id | varchar name
0            -           hello
1            0           world

And entity class:

@Entity
@Table(name = "mypack.A")
public class A
{
  @Id
  @Column(name = "ID")
  private int id;

  @Column(name = "REF_ID", nullable=true)
  private int ref_id;

  @Column(name = "NAME")
  private String name;
  // getters and setters

}

Row with id 1 refers to row with id 0. How can I do this kind of relation using Hibernate? I have an idea to create A class object inside that. Is it ok?

Upvotes: 0

Views: 40

Answers (1)

t0tec
t0tec

Reputation: 340

You can use instead of the property ref_id of type int use a reference to another A object.

@Entity
@Table(name = "mypack.A")
public class A implements Serializable {

  @Id
  @GeneratedValue
  @Column(name = "ID")
  private Long id;
  @ManyToOne(cascade = CascadeType.ALL)
  @JoinColumn(name = "REF_ID")
  private A refA;
  @Column(name = "NAME")
  private String name;
  // getters and setters
}

Upvotes: 1

Related Questions