How to query the database with MyBatis

MyBatis is an excellent persistence layer framework for Java development. It supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all JDBC code and manual setting of parameters and obtaining result sets. MyBatis can use simple XML or annotations to configure and map the mapping relationship between native types, interfaces and Java POJOs (Java objects).

To use MyBatis to query the database, you first need to create a database connection. Then, you can execute SQL queries through the SqlSession provided by MyBatis.

The following is a simple MyBatis query example:

  1. Create a database connection:
@Property("url")
private String url;

@Property("user")
private String user;

@Property("password")
private String password;

// ...

@SqlSession
public MyBatisSession getSession() {
    DataSource dataSource = new JdbcDataSource(url, user, password);
    return new MyBatisSession(dataSource);
}
  1. Create a Mapper interface:
@Mapper
public interface UserMapper {
    @Select("SELECT * FROM users WHERE username = #{user}")
    User getUser(@Param("user") String user);
}
  1. Inject the Mapper interface into the Java project:
@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;

    public User getUser(String user) {
        return userMapper.getUser(user);
    }
}
  1. Use the Mapper interface to obtain user information:
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User getUser(String user) {
        return userMapper.getUser(user);
    }
}

This example shows how to use MyBatis to query a database. By creating a database connection, creating a Mapper interface and a Java service class, you can easily use MyBatis to obtain user information in the database.

Guess you like

Origin blog.csdn.net/m0_59327517/article/details/132755339