Search code examples
javajsonhibernatejpahibernate-mapping

How do I map json column in hibernate-mapping file?


I'm trying to follow this blog on how to map a json to hibernate : https://vladmihalcea.com/how-to-map-json-objects-using-generic-hibernate-types. It does not say how to do the hibernate-mapping file (.hbm.xml).

How do I do it?

I have tried something like this, but its not working :

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.orange.model">
    <class name="Test_json" table="product_json">
        <id name="id" column="id">
            <generator class="increment"/>
        </id>
        <property name="jdoc" column="json" type="json" />
    </class>
</hibernate-mapping>

The java classes are :

// package and imports omitted

@XmlRootElement
@Entity
@Table(name="product_json")
@TypeDef(name = "json", typeClass = JsonType.class)
public class Test_json {
    
    @Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy = "increment")
    private int id;

    @Type(type = "json")
    @Column(name="json", columnDefinition ="json")
    private Jdoc jdoc;
    
    // getters and setters omitted
}

and

// package omitted

public class Jdoc {
    private int idprod;
    private String nameprod;
    private String description;

    // getters and setters omitted
}

Do I have to create a hibernate-mapping file for Jdoc class? If so, how do I link it to the Test_jdoc mapping?

Thanks in advance for your help.


Solution

  • Thanks to vladmihalcea, I was able to understand.
    Forget about hibernate mapping files.

    Do JPA annotation mapping !

    My solution to my problem :
    Instead of adding your class with <mapping resource="Test_json.hbm.xml" />.
    Add your class with code when creating sessionFactory :

    sessionFactory = new MetadataSources( registry )
                    .addAnnotatedClass(Test_json.class)
                    .buildMetadata().buildSessionFactory();