1 2 3 4 5 |
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.17.Final</version> </dependency> |
SessionFactory (jpa: EntityManagerFactory) – thread-safe (and immutable) representation of the mapping of the application domain model to a database
Session (jpa: EntityManager) – A single-threaded, short-lived object conceptually modeling a “Unit of Work”
StatelessSession – like JDBC
Transaction (jpa: EntityTransaction) – A single-threaded, short-lived object used by the application to demarcate individual physical transaction boundaries.
@PersistenceUnit injects an EntityManagerFactory
@PersistenceContext injects an EntityManager
Hibernate – hibernate.cfg.xml
1 2 3 4 5 |
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure() // configures settings from hibernate.cfg.xml .build(); sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory(); |
1 2 3 4 5 |
Session session = sessionFactory.openSession(); session.beginTransaction(); session.save( new Event( "Our very first event!", new Date() ) ); session.getTransaction().commit(); session.close(); |
JPA – persistence.xml
1 2 3 4 5 6 7 8 |
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="org.hibernate.tutorial.jpa"> ... </persistence-unit> </persistence> |
1 |
sessionFactory = Persistence.createEntityManagerFactory( "org.hibernate.tutorial.jpa" ); |
1 2 3 4 5 |
EntityManager entityManager = sessionFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.persist( new Event( "Our very first event!", new Date() ) ); entityManager.getTransaction().commit(); entityManager.close(); |
save or persist
save() – for transient save to db, return object(id), for detached create new one row
persist() – for transient save to db and return void, for detached object – PersistentObjectException. For transient doesn’t guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time
saveOrUpdate() – (only hibernate) doesn’t throw Exception on transient object.
merge or update
merge() – for transient and detached the same behavior: update a persistent entity instance with new field values from a detached entity instance, return new attached object.
update() – original hibernate method, return type is void, act on passed object (re-attach). Throws exception on transient entity.
Flush and Refresh
session.refresh() – reload object from database
Flush –
- before some query executions
- from org.hibernate.Transaction.commit()
- from Session.flush()
Flush ordering –
- all entity insertions in the same order the corresponding objects were saved using Session.save()
- all entity updates
- all collection deletions
- all collection element deletions, updates and insertions
- all collection insertions
- all entity deletions in the same order the corresponding objects were deleted using Session.delete()
Flush mode –
- only flush at commit time when the Hibernate Transaction API is used
- flush automatically using the explained routine,
- never flush unless flush() is called explicitly.
get or load
get(class, id) (jpa: find )- hit the database, return object or null if it not exists.
load(class, id) (jpa: getReference) – return proxy, hit the database when object requested, throws exception (jpa:EntityNotFoundException) when object not exists.
sort or ordered
sort – sorting in jvm with Comparator or native
order – use database order by
Inheritance mapping
MappedSuperclass – the parent classes, can’t be entities – super class doesn’t have own table. Superclass no longer has an @Entity annotation. @AttributeOverride – for renaming database column that different from super class column name.
Table-Per-Class – all the properties of a class, are in its table, so no join is required. The same as previous, super class also has a table.
Single Table – the entities from different classes with a common ancestor are placed in a single table. @DiscriminatorValue (@DiscriminatorFormula) – for this specific entity class so that your persistence provider can map each database record to a concrete entity class.
Joined Table – each class has its table and querying a subclass entity requires joining the tables. @PrimaryKeyJoinColumn – the primary key of the Subclass entity also has a foreign key constraint to the primary key of its parent entity.
Native query
1 2 |
Query q = em.createNativeQuery("SELECT a.id, a.version, a.firstname, a.lastname FROM Author a", Author.class); List<Author> authors = q.getResultList(); |
Named queries
1 2 3 4 |
@NamedQueries({ @NamedQuery(name = "@HQL_GET_ALL_ADDRESS", query = "from Address") }) @NamedNativeQueries({ @NamedNativeQuery(name = "@SQL_GET_ALL_ADDRESS", query = "select emp_id, address_line1, city, zipcode from Address") }) |
FetchType: N+1 SELECT’s Problem
FetchType.SELECT – N+1 problem is where one query is executed to fetch N records and N queries to fetch some relational records
can be resolved by using fetch join or using a Criteria
but fetch join doesn’t work with pagination
Lazy Loading
@Basic, @OneToMany, @ManyToOne, @OneToOne, and @ManyToMany annotations have an optional parameter called fetch. If this parameter is set to FetchType.LAZY
Build-time bytecode instrumentation (jpa)
Run-time bytecode instrumentation (jpa)
Run-time proxies (hibernate)
Bytecode enhancement
Custom user types
public class MoneyType implements BasicType
public class MoneyType implements UserType
public class MoneyType implements CompositeUserType
Collection types (hibernate)
Debug mode
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.use_sql_comments=true
Annotations
@Transient – not store to database
@Temporal – time, date or timestamp in datadase
@Table – name of mapped table
@Version – for optimistic locking
@ElementCollection (hibernate: @CollectionOfElements) like OneToMany but belongs to entity – Embeddable, cannot select, merge, update without main entity
1 2 3 4 5 |
@ElementCollection @CollectionTable( name="CUST_ADDRESS", joinColumns=@JoinColumn(name="OWNER_ID") ) |
JPA 2.1
Named Stored Procedures
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Converter(autoApply=true) public class BooleanTFConverter implements AttributeConverter<Boolean, String>{ @Override public String convertToDatabaseColumn(Boolean value) { if (Boolean.TRUE.equals(value)) { return "T"; } else { return "F"; } } @Override public Boolean convertToEntityAttribute(String value) { return "T".equals(value); } } |