database and relative
  • Introduction
  • database
  • SQL
  • different kinds of Database
  • JDBC
  • oracle
  • MySQL
  • hibernate1
  • JavaPersistence:HibernateandJPAFundamentals0
  • keys
  • NoSQL DB
Powered by GitBook
On this page
  • 1. trouble shooting
  • 2. entity VS value type
  • 3. Component Mapping(more classes than tables)
  • 4. primary key VS foreign key
  • 5. Mapping Associations
  • 6. Cascades
  • 7. Relationship
  • 8. Dirty Checking
  • 9. JPA
  • 9.2 JPA-Persistence-Context VS Persistence - Unit.Proper use of EntityManager and EntityManagerFactory
  • What is persistence-context?
  • 10. Caching Objects
  • 11. Lazy Fetching
  • 12. Equals & HashCode
  • 13. Query Language

Was this helpful?

JavaPersistence:HibernateandJPAFundamentals0

1. trouble shooting

1.1 creation failed.org.hibernate.service.spi.ServiceException: Unable to create requested service.

solution:

mysql driver version is not matching.

& make sure the database and table exists.

1.2 hibernate 4VS hibernate 5

hibernate 5 uses:

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

hibernate 4 uses:

    @GenerateValue(strategy=GenerationType.IDENTITY)

2. entity VS value type

An object of entity type has its own database identity(primary key value)

An object of value type has no database identity (primary key value); it belongs to an entity

Does the database identity of an object matters? Entity: Value Type

3. Component Mapping(more classes than tables)

a component is a part of a whole in such a way that if the whole is destroyed, all its parts are also destroyed with it.

@Embedded in the @Entity

@Embeddable in the value type which is part of Entity

4. primary key VS foreign key

Primary Key

Foreign Key

Primary key uniquely identify a record in the table

Foreign key is a field in the table that is primary key in another table

Primary Key can't accept null values

Foreign key can accept multiple null value

By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index.

Foreign key do not automatically create an index, clustered or non-clustered. You can manually create an index on foreign key.

We can have only one Primary key in a table.

We can have more than one foreign key in a table.

5. Mapping Associations

e.g.

    @ManyToOne
    @JoinColumn(name="guide_id")
    private Guide guide;

student has a guide. The are associated.

6. Cascades

Cascading the PERSIST operation, AKA Transitive Persistence

when save the student, the guide needs to be saved. We can save once by using:

session.persist(student);//both student & guide save to database
....
//Student class 
@ManyToOne(cascade={CascadeType.PERSIST})
@JoinColumn(name="guide_id")
private Guide guide;

CascadeType.REMOVE

session.delete(student);//delete the whole object graph of student
...
@ManyToOne(cascade={CascadeType.PERSIST, CascadeType.REMOVE})

7. Relationship

7.1 OneToMany Relationship

If the association is bidirectional, one of the sides(and only one) has to be the owner of the relationship.

The owner of the relationship is responsible for the association column(s) update.

e.g. the guide update won't update the student

Note:

  • Many side in a One-to-Many bi-directional relationship is (almost) always the owner side.

  • Owner is the entity that is persisted to the table that has the foreign key column.

7.2 OneToOne Relationship

  • to declare a side as not responsible for the relationship, the attribute mappedBy is used.

one table to be the owner.

7.3 ManyToMany Relationship

movie<-->actor Bi-directional

manyToMany

8. Dirty Checking

Dirty Checking is one of the features of hibernate. In dirty checking, hibernate automatically detects whether an object is modified (or) not and need to be updated. As long as the object is in persistent state i.e., bound to a particular Session(org.hibernate.Session). Hibernate monitors any changes to the objects and executes sql.

9. JPA

JPA is a Java specification for accessing, persisting, and managing data between Java objects and a relational database.

JPA provides guidelines that a framework can implement to be considered JPA compatible.

9.1

An EntityManager has a persistence context. It is First-level cache.

A cache is a copy of data, copy meaning pulled from but living outside the database.

9.2 JPA-Persistence-Context VS Persistence - Unit.Proper use of EntityManager and EntityManagerFactory

9.2.1 EntityManagerFactory and persistence-unit

An instance of the interface EntityManagerFactory is used to load a persistence-unit. We can get it via bootstrap class Persistence.

e.g.

EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");

EntityManagerFactory is thread safe so a single instance can be shared by multiple threads.

9.2.1.1 What is persistence-unit?

A persistence unit is a logical grouping that contains information like configuration of EntityManagerFactory, a set of entity classes, mapping metadata (can be loaded by scanning mapping annotations or from persistence.xml/orm.xml under META-INF directory). Each persistence-unit must have a unique name. An application can have one or more persistence units.

9.2.2 EntityManager and persistence-context

e.g.

EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPersistenceUnit");
EntityManager entityManager = emf.createEntityManager();

What is persistence-context?

An EntityManager instance is associated with a persistence-context. The persistence-context is a set of managed unique entity instances. EntityManger interacts with this context to manage entity instances and their lifecycle.

EntityManager is not thread-safe, so we should use only one instance per thread.

Each EntityManagerFactory instance provides EntityManager instances that are all configured in the same manner, i.e. all will be using the same persistence-unit. More than one EntityManagerFactory instances can be used per application which would probably be pointing to different set of entities and data-sources etc.

When the application has finished using the entity manager factory, and/or at application shutdown, the application should close the entity manager factory by callingemf.close(). Once an entity manager factory has been closed, all entity managers created from it are considered to be in the closed state as well.

10. Caching Objects

Persistence Context(and therefore a cache): First-Level Caching. Each Entity Manager has its own Cache.

First-level Caching scope: EntityManager

Second-level Caching scope: EntityManagerFactory

11. Lazy Fetching

Lazy Collection Fetching: A collection is fetched when the application invokes an operation upon that collection.

By default, collection associations(@OneToMany and @ManyToMany) are Lazily fetched.

If the associated entity want to be fetched with it, fetch = FetchType.EAGER is needed.

e.g.

@OneToMany(mappedBy="guide", cascade={CascadeType.PERSIST, fetch = FecthType.EAGER})

By default, single point associations(@OneToOne and @ManyToOne) are eagerly fetched.

12. Equals & HashCode

If you entity will be part of a Set collection, override its equals and hashcode methods.

using business key.

13. Query Language

JPQL: Java Persistence Query Language

HQL: Hibernate Query Language

e.g.

            Query query = entityManager.createQuery("select guide from Guide as guide");
            List<Guide> names=query.getResultList();

trouble1:

can't get Guide guide from table but guide.name can get.

Previoushibernate1Nextkeys

Last updated 5 years ago

Was this helpful?

http://www.logicbig.com/tutorials/java-ee-tutorial/jpa/entity-context/