Mappings: Primary Keys: @entity Public Class Author (
Mappings: Primary Keys: @entity Public Class Author (
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
...
}
www.thoughts-on-java.org
Hibernate with MySQL
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.AUTO,
generator = "native")
@GenericGenerator(name = "native", strategy = "native")
@Column(name = "id", updatable = false, nullable = false)
private Long id;
...
}
@Entity
@Immutable
public class BookView { … }
www.thoughts-on-java.org
Hibernate with MySQL
Queries: MySQL-specific functions and data types
As every other database, MySQL extends the SQL standard with a set
of custom functions and data types. Examples for that are the JSON
data type and the sysdate function.
These are not supported by JPA but thanks to Hibernate’s MySQL
dialect, you can use them anyways.
Query q = em.createQuery(
"SELECT a, sysdate() FROM Author a ");
List<Object[]> results = q.getResultList();
www.thoughts-on-java.org
Hibernate with MySQL
Queries: Stored Procedures
Since JPA 2.1, you can use a @NamedStoredProcedureQuery or a
StoredProcedureQuery to define a stored procedure call.
@NamedStoredProcedureQuery
The @NamedStoredProcedureQuery annotation allows you to define
the stored procedure call once and to reference it by its name in your
business code.
@NamedStoredProcedureQuery(
name = "calculate",
procedureName = "calculate",
parameters = {@StoredProcedureParameter(
mode = ParameterMode.IN,
type = Double.class, name = "x"),
@StoredProcedureParameter(
mode = ParameterMode.IN,
type = Double.class, name = "y"),
@StoredProcedureParameter(
mode = ParameterMode.OUT,
type = Double.class, name = "sum") })
StoredProcedureQuery query =
em.createNamedStoredProcedureQuery("calculate");
query.setParameter("x", 1.23d);
query.setParameter("y", 4d);
query.execute();
Double sum =
(Double) query.getOutputParameterValue("sum");
www.thoughts-on-java.org
Hibernate with MySQL
StoredProcedureQuery
The programmatic definition of a stored procedure call is very similar
to the annotation based approach I showed you in the previous
example.
StoredProcedureQuery query =
em.createStoredProcedureQuery("calculate");
query.registerStoredProcedureParameter("x", Double.class,
ParameterMode.IN);
query.registerStoredProcedureParameter("y", Double.class,
ParameterMode.IN);
query.registerStoredProcedureParameter("sum",
Double.class, ParameterMode.OUT);
That’s all you need to do define the stored procedure call. You can
then use it in the same way as the @NamedStoredProcedureQuery.
query.setParameter("x", 1.23d);
query.setParameter("y", 4d);
query.execute();
www.thoughts-on-java.org