How can I map a VISTA or STORED PROCEDURE from a sql server database with Hibernate in Java SE?
How can I map a VISTA or STORED PROCEDURE from a sql server database with Hibernate in Java SE?
You can map a View, but not a Stored Procedure.
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.
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.