marți, 7 aprilie 2009

Hibernate and Composite Keys

Hibernate is a powerful ORM(object relational mapping) very populat nowadays. In latest version, Hibernate comes with Hibernate Annotations. Using annotations you can avoid writting addition xml files for object mapping. In Java, we use hibernate for moving relational model to objective model.Above diagram descibe the following situation: we have several webhosting packages and several tehnology. Between them, we have a many-to-many relation. It's obvious in the database we have a composite primary key: (pachet,tehnologie). Below I write the code for describing the relation from image in terms of hibernate.

@Entity
@Table(name="tblpachete")
public class PachetGazduire
{
@Id
private int id;

@OneToMany(fetch=FetchType.EAGER, mappedBy="id.pachet")
private ArrayList tehnologii;

/* here we add other properties/methods */
}


@Entity
@Table(name="tbltehnologii")
public class Tehnologie
{
@Id
private int id;

/* here comes getter/setter */
}



/* This class implements the composite key */
@Embeddable
public class TehnologiiPachetPK
{
@ManyToOne
@JoinColumn(name="fk_pachet", referencedColumnName="id")
private PachetGazduire pachet;


@ManyToOne
@JoinColumn(name="fk_tehnologie", referencedColumnName="id")
private Tehnologie tehnologie;

/* here come other methods/properties */
}



@Entity
@Table(name="tbltehnologiipachet")
public class TehnologiiPachet
{
@Id
private TehnologiiPachetPK id;

int laCerere;
int nrConturi;
int pretLaCerere;

/* here comes other methods/properties */
}

You might test this code by generating getter/setter methods for every class. You also have to create the underlying tables. One simple solution it's to let hibernate create them for you: hibernate.hbm2ddl.auto = true(in hibernate.cfg.xml)

After you create the tables you populate them with data and everything should be just fine. Good luck.

Niciun comentariu:

Trimiteți un comentariu