dsk
dsk

Reputation: 657

Generics with Hibernate

Following class fail to load with the Hibernate

package com.project.alice.entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonProperty;

@Table
@Entity
 public class AnyInformation<T, K> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonProperty("id")
private long id;
@JsonProperty("parent")
@ManyToOne
private T parent;
@ManyToOne
@JsonProperty("parentType")
private K parentType;
@JsonProperty("informationType")
private String informationType;
@JsonProperty("information")
private String information;

public long getId() {
    return id;
}

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

public T getParent() {
    return parent;
}

public void setParent(T parent) {
    this.parent = parent;
}

public K getParentType() {
    return parentType;
}

public void setParentType(K parentType) {
    this.parentType = parentType;
}

public String getInformationType() {
    return informationType;
}

public void setInformationType(String informationType) {
    this.informationType = informationType;
}

public String getInformation() {
    return information;
}

public void setInformation(String information) {
    this.information = information;
}

}




org.hibernate.AnnotationException: 
Property com.project.alice.entities.AnyInformation.parent 
has an unbound type and no explicit target entity. 
Resolve this Generic usage issue or set an explicit target attribute 
(eg @OneToMany(target=) or use an explicit @Type

Please help me here.

Upvotes: 3

Views: 7508

Answers (1)

Bhushan
Bhushan

Reputation: 148

You should try something like -

@ManyToOne(targetEntity=Sample.class)
@JoinColumn(name = "<ID>")
private P parent;

@OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST, targetEntity=Sample.class)
private List<C> children;

Where, P and C extends Sample Class.

I hope it helps.

Note : As per my knowledge It can't be generic as you are expecting. You can not provide any object as a parameter. But the object should be related to the entity you are defining like Parent or Child. That's how it works in Hibernate.

Upvotes: 6

Related Questions