Convert Figma logo to code with AI

mybatis logomybatis-3

MyBatis SQL mapper framework for Java

19,687
12,809
19,687
210

Top Related Projects

Hibernate's core Object/Relational Mapping functionality

6,093

jOOQ is the best way to write SQL in Java

3,139

requery - modern SQL based query & persistence for Java / Kotlin / Android

1,959

The Jdbi library provides convenient, idiomatic access to relational databases in Java and other JVM technologies such as Kotlin, Clojure or Scala.

Quick Overview

MyBatis is a popular Java persistence framework that simplifies the implementation of database operations. It provides a layer of abstraction between Java code and SQL databases, allowing developers to work with objects instead of directly writing SQL queries.

Pros

  • Simplifies database operations by mapping Java objects to SQL statements
  • Offers great flexibility and control over SQL queries
  • Supports both XML and annotation-based configuration
  • Integrates well with Spring Framework and other Java technologies

Cons

  • Steeper learning curve compared to some ORM frameworks like Hibernate
  • Manual mapping between objects and database tables can be time-consuming
  • Less automation for database schema changes
  • Performance may be slightly lower than raw JDBC in some cases

Code Examples

  1. Basic SELECT query using XML mapping:
String statement = "com.example.mapper.UserMapper.selectUser";
User user = sqlSession.selectOne(statement, 1);
  1. INSERT operation using annotations:
@Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertUser(User user);
  1. Dynamic SQL using XML:
<select id="findActiveUsersByName" resultType="User">
  SELECT * FROM users
  WHERE status = 'ACTIVE'
  <if test="name != null">
    AND name LIKE #{name}
  </if>
</select>

Getting Started

  1. Add MyBatis dependency to your project (Maven example):
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.9</version>
</dependency>
  1. Create a MyBatis configuration file (mybatis-config.xml):
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
        <property name="username" value="root"/>
        <property name="password" value="password"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="com/example/mapper/UserMapper.xml"/>
  </mappers>
</configuration>
  1. Create a mapper interface and XML file for your database operations.

  2. Use SqlSessionFactory to create SqlSession and execute database operations:

String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

try (SqlSession session = sqlSessionFactory.openSession()) {
  UserMapper mapper = session.getMapper(UserMapper.class);
  User user = mapper.selectUser(1);
}

Competitor Comparisons

Hibernate's core Object/Relational Mapping functionality

Pros of Hibernate ORM

  • Full ORM solution with automatic SQL generation and object/relational mapping
  • Supports lazy loading and caching for improved performance
  • Provides a rich query language (HQL) for complex queries

Cons of Hibernate ORM

  • Steeper learning curve due to its complexity and feature-rich nature
  • Can be overkill for simple database operations
  • Performance overhead for simple CRUD operations

Code Comparison

Hibernate ORM:

@Entity
public class User {
    @Id
    private Long id;
    private String name;
    // Getters and setters
}

Session session = sessionFactory.openSession();
User user = session.get(User.class, 1L);

MyBatis:

public interface UserMapper {
    @Select("SELECT * FROM users WHERE id = #{id}")
    User getUser(Long id);
}

SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.getUser(1L);

MyBatis offers more control over SQL queries, while Hibernate ORM abstracts away most of the SQL, providing a more object-oriented approach. Hibernate is better suited for complex object relationships and large-scale applications, while MyBatis excels in scenarios where fine-grained SQL control is needed or for simpler database interactions.

6,093

jOOQ is the best way to write SQL in Java

Pros of jOOQ

  • Type-safe SQL queries with compile-time checking
  • Seamless integration with Java, allowing for fluent API usage
  • Extensive support for various database-specific features

Cons of jOOQ

  • Steeper learning curve due to its DSL approach
  • Requires code generation step for optimal type-safety
  • Commercial licensing for some databases and advanced features

Code Comparison

MyBatis-3:

<select id="selectPerson" parameterType="int" resultType="hashmap">
  SELECT * FROM PERSON WHERE ID = #{id}
</select>

jOOQ:

Result<Record> result = create.select()
    .from(PERSON)
    .where(PERSON.ID.eq(id))
    .fetch();

MyBatis-3 uses XML-based configuration for SQL queries, while jOOQ employs a fluent Java API for query construction. jOOQ provides stronger type-safety and better integration with Java code, but MyBatis-3 offers a more straightforward approach for developers familiar with SQL. MyBatis-3 is generally easier to set up and use for simple scenarios, while jOOQ shines in complex database interactions and when working with multiple database systems.

3,139

requery - modern SQL based query & persistence for Java / Kotlin / Android

Pros of requery

  • Modern, lightweight ORM with a fluent API for easier query building
  • Supports reactive programming with RxJava integration
  • Offers better performance for complex queries and large datasets

Cons of requery

  • Smaller community and ecosystem compared to MyBatis
  • Steeper learning curve for developers familiar with traditional SQL-based ORMs
  • Less extensive documentation and fewer learning resources available

Code Comparison

MyBatis:

<select id="selectPerson" resultType="Person">
  SELECT * FROM Person WHERE id = #{id}
</select>

requery:

Result<Person> result = data
    .select(Person.class)
    .where(Person.ID.eq(id))
    .get();

Summary

requery is a modern ORM that offers a more fluent API and better performance for complex queries, while MyBatis provides a more traditional SQL-based approach with a larger community and ecosystem. The choice between the two depends on project requirements, team expertise, and performance needs.

1,959

The Jdbi library provides convenient, idiomatic access to relational databases in Java and other JVM technologies such as Kotlin, Clojure or Scala.

Pros of JDBI

  • More lightweight and focused on Java 8+ features
  • Fluent API design for easier query building
  • Better support for functional programming paradigms

Cons of JDBI

  • Smaller community and ecosystem compared to MyBatis
  • Less comprehensive documentation and learning resources
  • Fewer advanced features for complex mapping scenarios

Code Comparison

JDBI:

Handle handle = jdbi.open();
List<User> users = handle.createQuery("SELECT * FROM users WHERE age > :age")
    .bind("age", 18)
    .mapTo(User.class)
    .list();

MyBatis:

SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> users = mapper.getUsersOlderThan(18);

Summary

JDBI offers a more modern and lightweight approach to database access, with a focus on Java 8+ features and functional programming. It provides a fluent API for query building, making it easier to construct and execute database operations.

MyBatis, on the other hand, has a larger community and more extensive documentation. It offers more advanced features for complex mapping scenarios and is well-suited for projects with intricate database interactions.

The choice between JDBI and MyBatis depends on project requirements, team expertise, and preference for API style. JDBI may be more appealing for newer projects leveraging modern Java features, while MyBatis might be preferred for larger, more complex applications with extensive database mapping needs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

MyBatis SQL Mapper Framework for Java

build Coverage Status Maven central Sonatype Nexus (Snapshots) License Stack Overflow Project Stats

mybatis

The MyBatis SQL mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using an XML descriptor or annotations. Simplicity is the biggest advantage of the MyBatis data mapper over object relational mapping tools.

Essentials

Contributions

Mybatis-core is now being auto formatted. Given nature of some code logic with mybatis, it is more appropriate to force a formatting structure manually for snippets such as sql statements. To do so, add following blocks around code.

  • // @formatter:off to start the block of unformatted code
  • // @formatter:on to end the block of unformatted code

If comment sections need same behaviour such as javadocs, note that the entire block must be around entire comment as direct usage does not properly indicate that formatter treats it all as one comment block regardless.

Tests

Mybatis-3 code runs more expressive testing depending on jdk usage and platform.

By default, we set <excludedGroups>TestcontainersTests</excludedGroups> which will exclude a subset of tests with @Tag('TestcontainersTests'). Further, if pre jdk 16, we will further exclude record classes from executions further reducing tests.

When using jdk 16+, we adjust the rule to <excludedGroups>TestcontainersTests,RequireIllegalAccess</excludedGroups>.

When we run on ci platform, we further make adjustments as needed. See here for details.

As of 2/20/2023, using combined system + jdk will result in given number of tests ran. This will change as tests are added or removed over time.

without adjusting settings (ie use as is, platform does not matter)

  • any OS + jdk 11 = 1730 tests
  • any OS + jdk 17 = 1710 tests
  • any OS + jdk 19 = 1710 tests
  • any OS + jdk 20 = 1710 tests
  • any OS + jdk 21 = 1710 tests

our adjustments for GH actions where platform does matter

  • windows + jdk 11 = 1730 tests

  • windows + jdk 17 = 1710 tests

  • windows + jdk 19 = 1710 tests

  • windows + jdk 20 = 1710 tests

  • windows + jdk 21 = 1710 tests

  • linux + jdk 11 = 1765 tests

  • linux + jdk 17 = 1745 tests

  • linux + jdk 19 = 1745 tests

  • linux + jdk 20 = 1745 tests

  • linux + jdk 21 = 1745 tests

  • mac + jdk 11 = 1730 tests

  • mac + jdk 17 = 1710 tests

  • mac + jdk 19 = 1710 tests

  • mac + jdk 20 = 1710 tests

  • mac + jdk 21 = 1710 tests