Hibernate Configuration, Key Mapping, and Inheritance Strategies in Java

Technology5.82 KB

Hibernate Configuration Properties

  • hibernate.dialect org.hibernate.dialect.SQLServerDialect
  • hibernate.connection.driver_class net.sourceforge.jtds.jdbc.Driver
  • hibernate.connection.url jdbc:jtds:sqlserver://bd;databaseName=ParcialAD_22
  • hibernate.connection.username ParcialAD_xx
  • hibernate.connection.password ParcialAD_xx
  • hibernate.connection.pool_size 2
  • hibernate.connection.autocommit true

Cache Settings

  • hibernate.cache.use_query_cache true
  • hibernate.cache.provider_class org.hibernate.cache.HashtableCacheProvider
  • #hibernate.proxool.pool_alias pool1
  • #hibernate.format_sql true
  • hibernate.show_sql true

Schema Generation

  • #hibernate.hbm2ddl.auto create-drop
  • #hibernate.hbm2ddl.auto create
  • #hibernate.hbm2ddl.auto update
  • hibernate.hbm2ddl.auto validate

Performance Settings

  • hibernate.max_fetch_depth 1
  • hibernate.jdbc.use_streams_for_binary true
  • hibernate.jdbc.batch_size 20

Transaction and Session Context

  • hibernate.transaction.factory_class org.hibernate.transaction.JDBCTransactionFactory
  • hibernate.current_session_context_class thread

Session Factory Utility Class

The following HibernateUtil class builds a single, shared SessionFactory and registers the annotated entity classes:

public class HibernateUtil
{
private static final SessionFactory sessionFactory;
static
{
try
{
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(ComponenteEntity.class);
config.addAnnotatedClass(AditivoEntity.class);
config.addAnnotatedClass(ProductoEntity.class);
config.addAnnotatedClass(ComposicionEntity.class);
sessionFactory = config.buildSessionFactory();
}
catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed. -->" + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}

Saving an Entity

public void save(Alumno alumno){
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(this.toEntity(alumno));
session.getTransaction().commit();
session.close();
}

Composite Key Mapping

1) Generating the Composite Key Class

public class ResultadoEntityKey implements Serializable

For each class:

@ManyToOne
@JoinColumn(name="identificador")
private AutoEntity auto;

@ManyToOne
@JoinColumn(name="numeroCarrera")
private CircuitoEntity circuito;

identificador and numeroCarrera are the ID columns in the database.

2) In the Resultado Class

@EmbeddedId
private ResultadoEntityKey key;

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

3) In the Remaining Related Classes

In each of the two classes connected to Resultado, create a list:

@OneToMany(mappedBy="key.circuito")
private List listaResultado;

Example Queries

  1. Query q = s.createQuery("FROM ResultadoEntity r WHERE posicion=1");
  2. "FROM ResultadoEntity r WHERE r.key.auto.numeroAuto = :idAuto"
  3. Query q = s.createQuery("FROM ResultadoEntity r WHERE r.key.auto.escuderia.numero = :IdEscuderia");
    q.setInteger("IdEscuderia", e.getNumero());

Association Table (Many-to-Many)

In the owning class, the inverseJoinColumns attribute must reference the ID of the non-owning side as it appears in the database.

@ManyToMany
@JoinTable(name="compuestoDe", joinColumns=@JoinColumn(name="codProductoE"), inverseJoinColumns=@JoinColumn(name="codProductoSM"))
private List componentes;

Inheritance Strategies

Table Per Class

In the parent class:

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class ProductoEntity

Define columns and the ID in the methods.

In the child classes: add @Entity and @Table.

Single Table

In the parent class:

@Entity
@Table(name = "repuestos")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="tipo", discriminatorType=DiscriminatorType.STRING)
public class RepuestoBean implements Serializable

In the child classes:

@Entity
@DiscriminatorValue("xxx")
public class ImportadoBean extends RepuestoBean

Joined Tables (Parent in the Middle)

In the parent class:

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name = "VEHICLE_TYPE") (optional)

In the child classes: add @Entity and @Table.

Download

PDF Word HTML