一、Mybatis介紹
Mybatis是一種基於Java編程語言的開源框架,可用於實現將SQL語句與Java程序相分離。Mybatis並不包含數據源或數據庫連接池,它僅負責管理SQL語句和結果集。Mybatis常用於使用傳統JDBC編程時所需要完成的大量準備工作,而且使用Mybatis開發的程序具有高度的靈活性和性能。
二、Mybatis的使用
Mybatis的使用可分為以下幾步:
第一步:在pom.xml文件中,添加Mybatis相應的依賴。
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
</dependencies>
第二步:配置Mybatis的映射文件,指定每一個映射文件與其對應的Java接口。
<mapper resource="org/mybatis/example/BlogMapper.xml" />
第三步:編寫Java接口,該接口中包含需要執行的SQL語句。
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{userId}")
User getUser(@Param("userId") String userId);
}
第四步:編寫調用Mybatis的Java程序。
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.getUser("123");
}
三、Mybatis中的一些特性
1、mybatis-config.xml
Mybatis的配置文件mybatis-config.xml是整個框架中最重要的一個文件,它包含了Mybatis全局配置參數、類型別名和映射文件的配置信息。在實際應用中,mybatis-config.xml的作用類似於Hibernate中的hibernate.cfg.xml文件。
以下是一個簡單的mybatis-config.xml文件示例:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<typeAliases>
<typeAlias type="com.example.domain.User" alias="User"/>
</typeAliases>
<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/mybatis"/>
<property name="username" value="mysql"/>
<property name="password" value="mysql"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mappers/user.xml"/>
</mappers>
</configuration>
2、映射文件
在Mybatis中,映射文件的作用是定義了一個或多個SQL語句和結果元映射。以user.xml為例,如下:
<mapper namespace="com.example.mapper.userMapper">
<resultMap id="userResultMap" type="com.example.domain.User">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="email" column="email"/>
<result property="phone" column="phone"/>
</resultMap>
<select id="getUserById" resultMap="userResultMap" parameterType="java.lang.String">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
映射文件中,定義了Namespace(命名空間)和一個或多個CRUD類型的方法等,具體可以參照Mybatis官方文檔進行理解。
3、動態SQL
動態SQL是Mybatis的一個非常實用的功能,它可以讓用戶編寫出靈活且功能強大的SQL語句。以下是一個例子:
<select id="getUserExt">
SELECT * FROM user WHERE
<if test="name != null">
name = #{name},
</if>
<if test="phone != null">
phone = #{phone},
</if>
<if test="email != null">
email = #{email},
</if>
</select>
如果用戶調用getUserExt方法時同時提供了name和phone參數,那麼生成的SQL語句如下:
SELECT * FROM user WHERE name = 'xxxx' and phone = 'xxxx';
四、Mybatis與Spring的整合
Spring是Java企業級開發中很具有代表性的開源框架,提供了全面的企業級應用程序支持,其中包括對Mybatis的支持。
Spring整合Mybatis的步驟如下:
第一步:在pom.xml文件中,添加Spring和Mybatis的依賴。
第二步:在Spring 的配置文件applicationContext.xml中,將所有屬性設置好,並且將DataSource、SqlSessionFactory和MapperScannerConfigurer註冊到Spring中。
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${dataSource.driver}"/>
<property name="url" value="${dataSource.url}"/>
<property name="username" value="${dataSource.username}"/>
<property name="password" value="${dataSource.password}"/>
<property name="initialSize" value="${dataSource.initialSize}"/>
<property name="maxActive" value="${dataSource.maxActive}"/>
</bean>
<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="com.example.mapper" />
</bean>
五、小結
Mybatis是一個優秀的Java持久層框架,提供了很多實用的功能。它的靈活性和高性能讓它成為了Java企業級開發的首選之一。通過以上的介紹和演示,相信大家已經對如何使用Mybatis以及Mybatis與Spring的整合有了一定的了解,希望這篇文章能夠對大家有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/293562.html