views:

38

answers:

2

How to generate id for entity using constructor parameters - is that possible ? I need that to make tree structure (category -> subcategories...) passing to constructor parent category id.

Category category = new Category(parentId);
CategoryDAO.add(category);
A: 

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

madhurtanwani
Also look at http://stackoverflow.com/questions/495536/hibernate-id-generator
madhurtanwani
A: 

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.

Pascal Thivent