How can I map a VISTA or a STORED PROCEDURE from an sql server database with Hibernate in java se?

0

How can I map a VISTA or STORED PROCEDURE from a sql server database with Hibernate in Java SE?

    
asked by bryanalexandercd 18.08.2018 в 23:57
source

1 answer

2

You can map a View, but not a Stored Procedure.

Map a View with Hibernate

The views, in general, are mapped in the same way as the tables. You just have to define an entity that maps the view with its specific name and that of its columns.

The difference is that a view should not be modified by Hibernate, and this is achieved with the Hibernate-specific annotation @Inmutable .

Example:

@Entity
@Talbe(name = "vista_Factura") // <--- nombre de la vista en la base de datos
@Immutable
public class VistaFactura {
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "id", updatable = false, nullable = false)
   private Long id;

   @Column
   private BigDecimal totaBruto;

   @Column
   private BigDecimal totalImpuestos;

   @Column
   private BigDecimal totalNeto;

   @Column
   private String observaciones;

   @Column
   private Instant fechaCreacion;

   //...
}

The @Inmutable annotation tells Hibernate to ignore all changes in this entity, but you can use it to get data from the database.

List<VistaFactura> listaFactura = em.createQuery("SELECT v FROM VistaFactura v", VistaFactura.class).getResultList();

In summary, you should treat the view as a normal table only that you can not insert / update values.

Call a Stored Procedure with Hibernate

Although they can not be mapped, so-called SQL natives can be called stored procedures using the createSQLQuery() of a Session of Hibernate.

Query query = session.createSQLQuery("CALL  nombreProcedimientoAlmacenado").addEntity(MiEntidad.class);

And if the stored procedure requires parameters:

Query query = session.createSQLQuery("CALL nombreProcedimientoAlmacenado(:parametro1)")
  .addEntity(MiEntidad.class)
  .setParameter("parametro1","valor");

And the results can be obtained like this:

List<MiEntidad> listaMisEntidades = query.list();

It is also possible to call Stored Procedures with annotations, @NamedStoredProcedureQuery for stored procedures and @StoredProcedureParameter for parameters, but I will not elaborate on the subject anymore.

    
answered by 19.08.2018 / 03:58
source