MyBatis是一款优秀的Java持久层框架,它消除了几乎所有的JDBC代码和手动设置参数以及获取结果集的过程。MyBatis通过简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
MyBatis入门基础
1. MyBatis核心组件
- SqlSessionFactoryBuilder: 用于创建SqlSessionFactory。
- SqlSessionFactory: 用于创建SqlSession。
- SqlSession: 用于执行SQL语句,管理事务和获取映射器(Mapper)。
2. 配置MyBatis
配置文件mybatis-config.xml是MyBatis的核心,其中定义了MyBatis的环境、事务管理器、数据源以及SQL映射文件的位置。
<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/mydb"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
3. 编写映射文件
映射文件定义了SQL语句与Java对象之间的映射关系。
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
MyBatis进阶使用
1. 动态SQL
MyBatis提供了动态SQL功能,可以根据条件动态生成SQL语句。
<select id="selectBlogsBySearch" resultType="Blog">
SELECT * FROM Blog
<where>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null">
AND author = #{author}
</if>
</where>
</select>
2. 一对一、一对多映射
MyBatis支持一对一和一对多映射。
<!-- 一对一映射 -->
<resultMap id="BlogResultMap" type="Blog">
<id property="id" column="id" />
<result property="title" column="title" />
<association property="author" column="author_id" javaType="Author">
<id property="id" column="id" />
<result property="username" column="username" />
</association>
</resultMap>
<!-- 一对多映射 -->
<resultMap id="AuthorResultMap" type="Author">
<id property="id" column="id" />
<result property="username" column="username" />
<collection property="blogs" ofType="Blog">
<id property="id" column="blog_id" />
<result property="title" column="title" />
</collection>
</resultMap>
MyBatis与Spring集成
MyBatis可以与Spring框架集成,简化开发过程。
<!-- Spring配置文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.mybatis.example"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
总结
MyBatis是一款非常强大的Java持久层框架,通过学习MyBatis,我们可以轻松实现高效的数据库操作。掌握MyBatis的核心组件、配置、映射文件、动态SQL以及与Spring的集成,将有助于我们在实际项目中更好地利用MyBatis的优势。
