Search code examples
mysqlhibernatespring-mvchibernate-mapping

How to store in one table an Entity composed by others Entity with Hibernate?


I am using SpringMVC + Hibernate and I am facing a problem that I struggle to solve. The situation is as follow :

I have this Entity :

@Entity
@Table( name = "T_inscription" )
public class T_inscription implements Serializable {

  @Id
  @GeneratedValue( strategy = GenerationType.IDENTITY )
  private Long           id_inscription;

  @Valid
  private Identite       identite;

  @Valid
  private ParamConnexion paramConnexion;
//........
}

This class :

public class Identite implements Serializable {

  @Size( min = 2 )
  @NotBlank
  @Pattern( regexp = "[\\p{L}\\p{Alpha} -]*" )
  @Column( name = "nom" )
  private String  nom;

  @Size( min = 2 )
  @NotBlank
  @Pattern( regexp = "[\\p{L}\\p{Alpha} -]*" )
  @Column( name = "prenom" )
  private String  prenom;
//....
}

And this one :

public class ParamConnexion implements Serializable {

  @Pattern( regexp = "[\\p{L}\\p{Alnum}-_]*" )
  @Size( min = 2 )
  @Transient
  private String                 identifiant;

  @Pattern( regexp = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\."
        + "[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*"
        + "@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" )
  @Column( name = "email" )
  private String                 email;
//.....
}

My table "T_inscription" contains these fields : "id_inscription","nom", "prenom", "identifiant", "email", etc...

My question is, how can I proceed to save the attributes of the classes "Identite" and "ParamConnexion" in the table "T_inscription" ?

I don't want to create a table per class. Is there a way to do this ?

I tried and I got this exeption : Unknown column 'identite' in 'field list'

It's normal because I do not have this field in my table and I don't want to create it, I just want to get the properties of "Identite".

Many thanks.


Solution

  • The two non-entity classes must be annotated with @Embeddable. The fields identite and paramConnexion must be annotated with Embedded Refer to the javadoc of those two annotations for more information.