简体   繁体   中英

Hibernate - persist embeddable resource

I'm just starting to learn Java database persistence using Hibernate ORM and have run into a problem which I haven't been able to resolve.

I have these two classes:

@Embeddable
public class Resource {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Resource() {
    }
}

@Entity
public class Group {

    @Embedded
    private Map<String, Resource> resources;

    @Id
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Map<String, Resource> getResources() {
        return resources;
    }

    public void setResources(Map<String, Resource> resources) {
        this.resources = resources;
    }

    public Group() {
        resources = new HashMap<String, Resource>();
    }
}

The Resource shouldn't have its own table because it shouldn't exist outside the Group scope. That's why I used the Embeddable, to be treated as a component.

To sum up I'd like to know how I can store these classes in a database using Hibernate ORM. The Resource class shouldn't be an Entity as it doesn't need its own class.

And I would prefer to use the mapping notations and not XML files.

As it is I get this error:

Syntax error in SQL statement "INSERT INTO GROUP[*] (NAME) VALUES (?) "; expected "identifier"; SQL statement:

It is possible to save all instances of Resource belonging to certain Group to the same database row with Group itself by creating class that wraps inside groups and saving it as Serializable to BLOB field in database.

Because such a solution asks more code and produces confusing data model, it is unlikely that you really want to limit yourself to have only one table.

If, as you said, Resource is fully owned by Group and you want to access them by some string key then @ElementCollection containing instances of embeddable Resource is solution (assuming that your version of Hibernate already have it):

@ElementCollection
private Map<String, Resource> resources;

If you do not have access collection of Resource by name, then following is sufficient

@ElementColection
private Set<Resource> resources;

For more examples about fine tuning your element collection can be found from: Java Persistence/ElementCollection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM