Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use a custom class as a JPA Id

I have a custom class which I have to use as Id for an entity. It looks as follows

public class ProductId {
private final String id;

public ProductId(String id) {
    this.id = id;
}

public String getId() {
    return id;
}

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (!(o instanceof ProductId)) {
        return false;
    }

    ProductId productId = (ProductId) o;

    if (!id.equals(productId.id)) {
        return false;
    }

    return true;
}

@Override
public int hashCode() {
    return id.hashCode();
}

}

How can I use this as Id column for a JPA entity. Would it be along the lines of

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private ProductId id;

I am getting inspiration and guidance from code generated by Spring ROO

like image 256
geoaxis Avatar asked Sep 21 '25 04:09

geoaxis


1 Answers

You can annotate your ID class with @Embeddable and annotate the field in your final entity as @EmbeddedId.

See: http://download.oracle.com/javaee/6/api/javax/persistence/EmbeddedId.html

like image 89
jpkrohling Avatar answered Sep 22 '25 17:09

jpkrohling