MyBatis概述
MyBatis是一個優秀的持久層框架,它支持定制化SQL、存儲過程以及高級映射。MyBatis避免了幾乎所有的JDBC代碼和手動設置參數以及獲取結果集的過程。
核心特點
優勢:
- SQL語句與Java代碼分離,便于維護
- 支持動態SQL,靈活性高
- 提供了強大的映射功能
- 與Spring框架集成良好
- 學習成本相對較低
與其他框架對比:
- 相比Hibernate:更輕量級,SQL可控性更強
- 相比JDBC:減少了大量樣板代碼
- 相比JPA:更適合復雜查詢和性能優化
MyBatis核心組件
1. SqlSessionFactory
// 創建SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
2. SqlSession
// 獲取SqlSession
SqlSession session = sqlSessionFactory.openSession();
try {// 執行操作UserMapper mapper = session.getMapper(UserMapper.class);User user = mapper.selectUser(1);
} finally {session.close();
}
3. Mapper接口
public interface UserMapper {User selectUser(int id);List<User> selectAllUsers();void insertUser(User user);void updateUser(User user);void deleteUser(int id);
}
4. XML映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper"><select id="selectUser" parameterType="int" resultType="User">SELECT * FROM users WHERE id = #{id}</select><insert id="insertUser" parameterType="User">INSERT INTO users (name, email) VALUES (#{name}, #{email})</insert>
</mapper>
IDEA中的MyBatis開發
1. 項目創建與依賴配置
Maven依賴:
<dependencies><!-- MyBatis核心依賴 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.13</version></dependency><!-- 數據庫驅動 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency><!-- Spring Boot集成(可選) --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.2</version></dependency>
</dependencies>
2. IDEA插件推薦
MyBatis相關插件:
- MyBatis Log Plugin:日志格式化顯示
- MyBatis Mapper Generator:代碼生成
- Free MyBatis Plugin:XML與Mapper跳轉
- MyBatis Plus:增強功能支持
3. 配置文件設置
mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatis_db"/><property name="username" value="root"/><property name="password" value="password"/></dataSource></environment></environments><mappers><mapper resource="mapper/UserMapper.xml"/></mappers>
</configuration>
4. 實體類設計
public class User {private Integer id;private String name;private String email;private Date createTime;// 構造方法、getter、setter省略
}
5. Mapper接口與XML映射
UserMapper.java:
@Mapper
public interface UserMapper {@Select("SELECT * FROM users WHERE id = #{id}")User selectById(Integer id);List<User> selectAll();@Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})")@Options(useGeneratedKeys = true, keyProperty = "id")void insert(User user);void update(User user);@Delete("DELETE FROM users WHERE id = #{id}")void deleteById(Integer id);
}
UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper"><resultMap id="userResultMap" type="User"><id property="id" column="id"/><result property="name" column="name"/><result property="email" column="email"/><result property="createTime" column="create_time"/></resultMap><select id="selectAll" resultMap="userResultMap">SELECT id, name, email, create_time FROM users</select><update id="update" parameterType="User">UPDATE users SET name = #{name},email = #{email}WHERE id = #{id}</update><!-- 動態SQL示例 --><select id="selectByCondition" parameterType="User" resultMap="userResultMap">SELECT * FROM users<where><if test="name != null and name != ''">AND name LIKE CONCAT('%', #{name}, '%')</if><if test="email != null and email != ''">AND email = #{email}</if></where></select>
</mapper>
動態SQL詳解
1. if標簽
<select id="selectByCondition" parameterType="User" resultType="User">SELECT * FROM users<where><if test="name != null and name != ''">AND name = #{name}</if><if test="email != null">AND email = #{email}</if></where>
</select>
2. choose、when、otherwise
<select id="selectByIdOrName" parameterType="User" resultType="User">SELECT * FROM users<where><choose><when test="id != null">id = #{id}</when><when test="name != null and name != ''">name = #{name}</when><otherwise>1 = 1</otherwise></choose></where>
</select>
3. foreach標簽
<select id="selectByIds" parameterType="list" resultType="User">SELECT * FROM users WHERE id IN<foreach collection="list" item="id" open="(" close=")" separator=",">#{id}</foreach>
</select>
Spring Boot集成
1. 配置文件
# application.yml
mybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: com.example.entityconfiguration:map-underscore-to-camel-case: truespring:datasource:url: jdbc:mysql://localhost:3306/mybatis_dbusername: rootpassword: passworddriver-class-name: com.mysql.cj.jdbc.Driver
2. 主啟動類
@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
3. Service層實現
@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public User getUserById(Integer id) {return userMapper.selectById(id);}public List<User> getAllUsers() {return userMapper.selectAll();}@Transactionalpublic void saveUser(User user) {userMapper.insert(user);}
}
IDEA開發技巧
1. 代碼生成器使用
MyBatis Generator配置:
<generatorConfiguration><context id="MySQLTables" targetRuntime="MyBatis3"><jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/mybatis_db"userId="root"password="password"/><javaModelGenerator targetPackage="com.example.entity" targetProject="src/main/java"/><sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/><javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"/><table tableName="users" domainObjectName="User"/></context>
</generatorConfiguration>
2. 調試技巧
- 使用MyBatis Log Plugin查看SQL執行情況
- 在IDEA中設置斷點調試Mapper方法
- 利用Database工具直接測試SQL語句
3. 性能優化
- 合理使用緩存機制
- 避免N+1查詢問題
- 使用批量操作提高效率
- 監控SQL執行計劃
- 命名規范:Mapper接口與XML文件保持一致的命名
- 事務管理:合理使用@Transactional注解
- 異常處理:統一處理數據訪問異常
- 參數驗證:在Service層進行業務邏輯驗證
- 日志記錄:記錄關鍵操作的執行日志