MyBatis简介
MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集的过程。MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
入门准备
环境搭建
- Java开发环境:确保你的电脑上安装了Java开发环境,并配置好环境变量。
- IDE:选择一款IDE,如IntelliJ IDEA或Eclipse,以便更方便地编写和调试代码。
- Maven:MyBatis推荐使用Maven进行依赖管理。
Maven依赖
在你的pom.xml文件中添加以下依赖:
<dependencies>
<!-- MyBatis核心依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
</dependencies>
核心概念
Mapper接口
Mapper接口定义了操作数据库的方法,MyBatis会通过XML或注解生成相应的SQL语句。
public interface UserMapper {
User selectById(int id);
}
XML映射文件
XML映射文件用于配置SQL语句和结果映射。
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectById" resultType="com.example.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
配置文件
配置文件用于配置数据库连接信息等。
<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/test"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
实践操作
创建数据库
首先,你需要创建一个数据库和一个表。
CREATE DATABASE test;
USE test;
CREATE TABLE user (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT
);
插入数据
在UserMapper.xml中添加以下SQL语句:
<insert id="insertUser" parameterType="com.example.User">
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
在Java代码中执行插入操作:
try {
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User();
user.setName("张三");
user.setAge(20);
mapper.insertUser(user);
session.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
}
查询数据
在UserMapper.xml中添加以下SQL语句:
<select id="selectByName" resultType="com.example.User">
SELECT * FROM user WHERE name = #{name}
</select>
在Java代码中执行查询操作:
try {
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectByName("张三");
System.out.println(user.getName() + " " + user.getAge());
session.close();
} catch (Exception e) {
e.printStackTrace();
}
高级特性
动态SQL
MyBatis支持动态SQL,可以使用<if>, <choose>, <when>, <otherwise>等标签实现。
<select id="selectUsers" resultType="User">
SELECT * FROM user
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
关联映射
MyBatis支持关联映射,可以方便地处理一对多、多对多等关系。
<resultMap id="userResultMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<collection property="orders" ofType="Order">
<id property="id" column="id"/>
<result property="orderNo" column="order_no"/>
<result property="price" column="price"/>
</collection>
</resultMap>
总结
MyBatis是一款功能强大的持久层框架,它可以帮助我们高效地构建持久层应用。通过本文的介绍,相信你已经对MyBatis有了初步的了解。在实际开发中,你需要不断地实践和探索,才能更好地掌握MyBatis的强大功能。祝你学习愉快!
