Home > Backend Development > PHP Tutorial > Java backend development: using MyBatis for data access

Java backend development: using MyBatis for data access

PHPz
Release: 2023-06-17 09:50:02
Original
1126 people have browsed it

Java back-end development: using MyBatis for data access

MyBatis is an excellent Java persistence framework that is widely used in Java back-end development. MyBatis can effectively help developers realize the data access process and shorten the application development cycle.

This article will introduce the application of MyBatis in Java back-end development, including how to configure the MyBatis environment, how to use MyBatis for data access, etc.

  1. MyBatis environment configuration

You need to configure the environment before using MyBatis. Below we briefly introduce how to configure it.

1.1 Database configuration

MyBatis needs to connect to the database through a configuration file. You need to create a configuration file named "mybatis-config.xml" in the resources directory.

Configuration data source:

<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 此处配置Mapper文件 -->

    </mappers>
</configuration>
Copy after login

1.2 Mapper configuration

Mapper is the implementation class of the Dao interface. You need to associate MyBatis with Mapper through a configuration file. The correlation method is as follows:

<mappers>
    <!-- 配置Mapper文件 -->
    <mapper resource="com/test/userMapper.xml"/>

</mappers>
Copy after login

Each SQL statement defined in the Mapper configuration file corresponds to a method in the Mapper interface class. Therefore, when defining the Mapper interface method, it is best to indicate the corresponding SQL statement. .

Mapper interface class example:

public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    public User selectUserById(int id);

    @Insert("INSERT INTO user (username, password) VALUES (#{username}, #{password})")
    public int addUser(User user);

    @Update("UPDATE user SET password = #{password} WHERE id = #{id}")
    public int updateUserById(User user);

    @Delete("DELETE FROM user WHERE id = #{id}")
    public int deleteUserById(int id);
}
Copy after login
  1. MyBatis use

After completing the environment configuration, you can use MyBatis for data access.

When using MyBatis in a Java project, you need to create a SqlSessionFactory object according to the configuration file, then create a SqlSession object through the SqlSessionFactory object, and finally perform data access through the SqlSession object.

2.1 SqlSessionFactory

SqlSessionFactory is a factory class for creating SqlSession. In the MyBatis environment, there are many ways to create SqlSessionFactory objects, such as through the SqlSessionFactoryBuilder class, through XML files, etc.

Create a SqlSessionFactory object through SqlSessionFactoryBuilder:

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

2.2 SqlSession

SqlSession is one of the most important classes in MyBatis for completing data access. All database operations are through the SqlSession object Completed.

Create a SqlSession object through SqlSessionFactory:

SqlSession session = sqlSessionFactory.openSession();
Copy after login

Use the SqlSession object to access the database:

// 获取Mapper接口对象
UserMapper userMapper = session.getMapper(UserMapper.class);

// 调用Mapper方法获取数据
User user = userMapper.selectUserById(1);

// 事务提交
session.commit();

// 关闭SqlSession对象
session.close();
Copy after login
  1. MyBatis application case

Let’s do this Let's look at an actual MyBatis application case and demonstrate the use of MyBatis by querying user information.

3.1 Define Mapper interface

public interface UserMapper {
    public User selectUserById(int id);
}
Copy after login

3.2 Define User class

public class User {
    private int id;
    private String username;
    private String password;
    private String email;
    //...getter/setter
}
Copy after login

3.3 Write Mapper configuration file

<mapper namespace="com.test.UserMapper">
    <select id="selectUserById" resultType="User">
        SELECT * FROM user WHERE id = #{id}
    </select>
</mapper>
Copy after login

3.4 Write code for database access

// 读取MyBatis配置文件并创建SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

// 使用SqlSessionFactory对象创建SqlSession对象
SqlSession session = sqlSessionFactory.openSession();

// 通过SqlSession获取Mapper接口对象
UserMapper mapper = session.getMapper(UserMapper.class);

// 调用Mapper接口获取数据
User user = mapper.selectUserById(1);
System.out.println(user);

// 事务提交并关闭Session资源
session.commit();
session.close();
Copy after login
  1. Summary

MyBatis is a very excellent Java persistence framework that can help developers complete the data access process efficiently. This article introduces the application of MyBatis in Java back-end development, including environment configuration, usage and application case display. We believe that this article can provide a good reference for developers who want to learn MyBatis data access.

The above is the detailed content of Java backend development: using MyBatis for data access. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template