How to execute SQL statements in MyBatis?

In MyBatis, executing SQL statements can be achieved using Mapper interfaces and mapping files. Here are the general steps:

1. Create a Mapper interface: Define the SQL statements to be executed in the Mapper interface, such as queries, updates, deletions, and other operations.

public interface UserMapper {
    User getUserById(Long id);
}

2. Create a mapping file (XML file): Configure the mapping relationship between SQL statements and Mapper interface methods in the mapping file.

<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
    <select id="getUserById" resultType="User">
        SELECT * FROM user WHERE id = #{id}
    </select>
</mapper>

3. Configure MyBatis by setting up the configuration file, where you can configure the data source and mapping files.

<!-- mybatis-config.xml -->
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.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>

Get the SqlSession object and execute SQL statements: Obtain the SqlSession object in the code, then execute SQL statements through the methods of the Mapper interface.

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1L);

sqlSession.close();

By following these steps, you can execute SQL statements in MyBatis and retrieve the results. MyBatis automatically maps the results to the specified Java objects, simplifying the process of data manipulation.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds