Hibernate: How to generate Id from entity constructor parameters?
How to generate id for entity using constructor parameters - is that possible ? I need that to make tree structure (category -> subcategories...) passing 开发者_JAVA百科to constructor parent category id.
Category category = new Category(parentId);
CategoryDAO.add(category);
One idea would be to use "id" "generators" from Hibernate. See docs here : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-id
Looking at your use case, the "assigned" or "class" generators seem a fit
This does not directly answer your question but, unless I misunderstood your requirements, what you actually want is to model a self-referencing association, something like this:
@Entity
public class Category {
@Id @GeneratedValue
private Long id;
private String name;
@ManyToOne(optional=true)
private Category parent;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private Set<Categories> subCategories;
// ...
public void addToSubCategories(Category category) {
category.setParent(this);
this.subCategories.add(category);
}
}
If this is not what you want, and if you don't want to use a generated identifier, then simply don't use the @GeneratedValue
annotation and assign the identifier manually (in the constructor, using the setter, anything). But I fail to see why you'd need this.
精彩评论