@Column not working in sub classes in Java + Hibernate

Viewed 126

This question is related to:

How to access child element using @XmlElement with Hibernate

xml

<person>
    ...

    <phone>
        <area>111</area>
        <number>123-4567</number>
    </phone>
</person>

I have a class to unmarshal from XML

@XmlRootElement(name="person")
@XmlAccessorType(XmlAccessType.FIELD)
@Entity
@Table(name = "person", schema = "test")
public class UserLinkedIn {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int id;
    // ...

    @XmlElement(name = "name")
    @Column(name = "name")
    int name; // this works, I get the name in my database

    @Transient
    @XmlElement(name = "phone")
    private Phone phone;

    @XmlRootElement(name = "phone")
    static class Phone {
        @XmlElement(name = "area")
        @Column(name = "phone-area")
        int area; // is 111

        @XmlElement(name = "number")
        @Column(name = "phone-number")
        int number; // is 123-4567
    }
}

My table:

table:
    id
    name
    phone-area
    phone-number

I am able to get the data correctly, but when I insert into my database i get 0 instead of 111 for area.

Why my "phone-area" and "phone-number" are not getting populated in my table?

1 Answers

You are using @Transient annotation, which means it won't be serialized into db. You are just getting a column default value 0 probably.

Another thing is that you are not utilizing @Embeddable nested object definition at all, check this

You should have the following nested object;

@Embeddable
@XmlRootElement(name = "phone")
public static class Phone {

    @XmlElement(name = "area")
    @Column(name = "phone-area")
    private Integer area;

    @XmlElement(name = "number")
    @Column(name = "phone-number")
    private Integer number;

    // getter, setters
}

With @Embedded on its decleration in parent entity;

@Embedded
@XmlElement(name = "phone")
private Phone phone;

Also, I assume you have getters, setters defined for these fields...

Another problem is that using primitive types, it is almost always better to avoid them withing entities.

Related