/java/

Hibernate. Xml component & @Embedded Annotation

2015-03-10 20:00:29

This is a continuation of How to start play with Hibernate.

Sometimes we want to split out Entity into smaller pieces, but on the same time, we can't or we don't want to make changes in db. In this scenerio we can use Component / @Embeded approach.

Start

For example we have something like this:

package pl.btbw.entity;

import javax.persistence.*;

@Entity
@Table(name = "post")
public class PostEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "type")
    private String type;

    @Column(name = "subtype")
    private String subtype;

    @Column(name = "category")
    private int category;

    //.. more properties 
    //.. set & get
}

And we decide to split this class into smaller:

Splitted version

package pl.btbw.entity;

import javax.persistence.*;

@Entity
@Table(name = "post")
public class PostEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "name")
    private String name;

    @Embedded
    private PostGroup postGroup = new PostGroup();

    public PostAnnotationEntity() {
    }

    // .. set & get
}

package pl.btbw.entity;

import javax.persistence.Column;

public class PostGroup {

    @Column(name = "type")
    private String type;

    @Column(name = "subtype")
    private String subtype;

    @Column(name = "category")
    private int category;

    public PostGroup() {
    }

    // ... set & get
}

Note that we have new Annotation @Embedded, it handles everything.

Of course, if you want to use xml, then remove all Annotation from these class, and use this:

<?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?>
<!DOCTYPE hibernate-mapping PUBLIC &quot;-//Hibernate/Hibernate Mapping DTD//EN&quot;
        &quot;http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd&quot;>

<hibernate-mapping>
<class name='"pl.btbw.entity.PostEntity"' table='"post"'>
<meta attribute='"class-description"'/>
            some description


        <id column='"id"' name='"id"' type='"java.lang.Integer"'>
<generator class='"identity"/'>
</generator></id>
<property column='"name"' name='"name"' type='"java.lang.String"/'>
<component name='"postGroup"'>
<property column='"type"' name='"type"' type='"java.lang.String"/'>
<property column='"subtype"' name='"subtype"' type='"java.lang.String"/'>
<property column='"category"' name='"category"' type='"java.lang.Integer"/'>
</property></property></property></component>
</property></class>
</hibernate-mapping>

here we have new component element.

whole code on GitHub