通过XML方式配置实现Mybatis,需要步骤如下:
- 引入Mybatis依赖(以Maven为例)
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
- 创建Mybatis配置文件mybatis-config.xml,其中包含两个重要的节点,如下:
(1)<typeAliases>
:用于定义类型别名,例如Java类名太长,需要使用别名来简化,如下示例:
<typeAliases>
<typeAlias type="com.example.User" alias="User"/>
</typeAliases>
(2)<mappers>
:用于引入Mapper映射文件,如下示例:
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
- 创建Mapper映射文件(例如:UserMapper.xml),引入命名空间,定义SQL语句、参数等,如下示例:
<mapper namespace="com.example.mapper.UserMapper">
<select id="getUserById" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
...
</mapper>
- 在Java代码中创建SqlSessionFactory,使用该对象获取SqlSession实例来执行SQL语句,如下:
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("com.example.mapper.UserMapper.getUserById", 1);
sqlSession.close();
以上为通过XML方式配置并实现Mybatis的完整攻略。
下面提供两个示例:
示例一:
创建一个UserMapper接口,其中定义getUserById方法,在mybatis-config.xml中引入该接口,示例代码如下:
public interface UserMapper {
User getUserById(Integer id);
}
在mybatis-config.xml中引入该接口,如下:
<mappers>
<mapper class="com.example.mapper.UserMapper"/>
</mappers>
执行SQL语句的代码如下:
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1);
sqlSession.close();
示例二:
创建一个resultMap来处理查询结果,示例代码如下:
<mapper namespace="com.example.mapper.UserMapper">
<resultMap id="UserMap" type="com.example.User">
<id column="id" property="id" />
<result column="username" property="username" />
<result column="password" property="password" />
</resultMap>
<select id="getUserById" resultMap="UserMap">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:如何通过XML方式配置并实现Mybatis - Python技术站