Skip to content

JPA, Hibernate, and MyBatis Core Object Comparison

In Java persistence frameworks, JPA, Hibernate, and MyBatis are popular tools, each providing different persistence models and mechanisms. Here's a comparison of the core objects in JPA, Hibernate, and MyBatis, to help understand their differences and suitable use cases.

1. Overview of Core Objects

Feature JPA (Java Persistence API) Hibernate (A JPA implementation) MyBatis
Configuration Object EntityManagerFactory SessionFactory SqlSessionFactory
Session Management Object EntityManager Session SqlSession
Transaction Management Object EntityTransaction (Non-JTA) Transaction SqlSession
Query Object JPQL Queries (TypedQuery) HQL Queries (Query) SQL Queries (Mapper interface or XML)
Configuration File persistence.xml hibernate.cfg.xml mybatis-config.xml
Object Mapping Mechanism Annotation or XML-based mapping Annotation or XML-based mapping Explicit SQL and Java method mapping
Caching Mechanism JPA-defined caching First-level cache, second-level cache First-level cache, optional second-level cache

2. Session Management Core Objects

2.1 JPA: EntityManager

  • Responsibilities: EntityManager is the core interface in JPA used to manage entities and database operations. It handles CRUD operations, queries, and persistence context management.
  • Lifecycle: Usually short-lived and closed after each session.
  • Use Cases:
  • Manage the lifecycle of entity objects (persist(), merge(), remove()).
  • Execute JPQL queries.
  • Manage transactions (uses EntityTransaction for non-JTA environments).

  • Example: java EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPU"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); User user = em.find(User.class, 1); em.getTransaction().commit(); em.close();

2.2 Hibernate: Session

  • Responsibilities: Session is the core interface in Hibernate, similar to JPA's EntityManager, for performing persistence operations. It manages entity lifecycle and Hibernate's first-level cache.
  • Lifecycle: Typically tied to a database session, used once per session and closed afterward.
  • Use Cases:
  • Manage persistent entity objects (save(), update(), delete()).
  • Supports Hibernate-specific features like batch inserts, native SQL queries, and HQL queries.

  • Example: java SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); User user = session.get(User.class, 1); tx.commit(); session.close();

2.3 MyBatis: SqlSession

  • Responsibilities: SqlSession is the main interface in MyBatis for executing SQL queries and managing transactions. Unlike JPA and Hibernate, MyBatis interacts directly with SQL.
  • Lifecycle: SqlSession is short-lived and typically closed after each database operation.
  • Use Cases:
  • Execute explicit SQL queries and interact with the database.
  • Manage transactions (commit() and rollback()).
  • Retrieve mapper interfaces (Mapper).

  • Example: java SqlSession session = sqlSessionFactory.openSession(); try { User user = session.selectOne("UserMapper.selectUser", 1); session.commit(); } finally { session.close(); }


3. Query and Mapping

3.1 JPA: JPQL (Java Persistence Query Language)

  • Query Style: JPA uses JPQL, which is similar to SQL but operates on entity classes instead of database tables.
  • Query Object: TypedQuery or Query.
  • Mapping Mechanism: JPA uses annotations or XML to map entity classes to database tables.

  • Example: java String jpql = "SELECT u FROM User u WHERE u.name = :name"; TypedQuery<User> query = em.createQuery(jpql, User.class); query.setParameter("name", "John"); List<User> users = query.getResultList();

3.2 Hibernate: HQL (Hibernate Query Language)

  • Query Style: Hibernate uses HQL, similar to JPQL but with additional support for Hibernate-specific features.
  • Query Object: Query.
  • Mapping Mechanism: Similar to JPA, Hibernate uses annotations or XML to map entities to the database.

  • Example: java String hql = "FROM User WHERE name = :name"; Query query = session.createQuery(hql); query.setParameter("name", "John"); List<User> users = query.list();

3.3 MyBatis: SQL Queries

  • Query Style: MyBatis uses explicit SQL queries. The queries are defined in XML or through annotations, giving the developer full control.
  • Mapping Mechanism: SQL results are mapped to Java objects through manually defined Mapper interfaces or XML files.

  • Example: java List<User> users = session.selectList("UserMapper.selectUsersByName", "John");

  • Mapper XML Definition: xml <select id="selectUsersByName" parameterType="string" resultType="User"> SELECT * FROM users WHERE name = #{name} </select>


4. Transaction Management

4.1 JPA: EntityTransaction / JTA

  • Transaction Management: In non-JTA environments, EntityTransaction is used to manage transactions. In Java EE environments, JPA uses JTA (Java Transaction API) for container-managed transactions.
  • Example: java em.getTransaction().begin(); User user = new User(); em.persist(user); em.getTransaction().commit();

4.2 Hibernate: Transaction

  • Transaction Management: Hibernate provides its own Transaction interface for explicit transaction management. It can also be used with JTA.
  • Example: java Transaction tx = session.beginTransaction(); session.save(user); tx.commit();

4.3 MyBatis: SqlSession

  • Transaction Management: MyBatis transactions are managed by the SqlSession. The commit() and rollback() methods handle transaction commits and rollbacks.
  • Example: java SqlSession session = sqlSessionFactory.openSession(); try { session.insert("UserMapper.insertUser", user); session.commit(); } catch (Exception e) { session.rollback(); } finally { session.close(); }

5. Caching Mechanism

5.1 JPA: First-Level Cache and Optional Second-Level Cache

  • First-Level Cache: Managed automatically by the EntityManager, caching entity states within a session.
  • Second-Level Cache: JPA allows the use of second-level caching, but it depends on the specific implementation (e.g., Hibernate).

5.2 Hibernate: First-Level Cache and Second-Level Cache

  • First-Level Cache: Provided by the Session, each session has its own cache.
  • Second-Level Cache: SessionFactory supports optional second-level caching that is shared across sessions.

5.3 MyBatis: First-Level and Optional Second-Level Cache

  • First-Level Cache: Provided by the SqlSession, enabled by default and scoped to the session.
  • Second-Level Cache: MyBatis supports optional second-level caching, but it must be explicitly configured.

Summary

Feature JPA Hibernate MyBatis
Operation Model Entity-based with JPQL Entity-based with HQL SQL-based with Mapper interfaces
Transaction Management EntityTransaction or JTA Transaction or JTA SqlSession
Caching First-level cache, optional second-level cache First-level cache, optional second-level cache First-level cache, optional second-level cache
Configuration Complexity Moderate (annotation or XML mapping) Moderate (annotation or XML mapping) Low (explicit SQL and manual mapping)

If you want to explore more details about the core objects in JPA, Hibernate, or MyBatis, feel free to ask!