MyBatis简介
MyBatis是一个优秀的持久层框架,它消除了几乎所有的JDBC代码和手动设置参数以及获取结果集的工作。MyBatis可以让我们以更加简单的方式操作数据库,它支持定制化SQL、存储过程以及高级映射。
入门指南
1. 环境搭建
首先,我们需要在项目中引入MyBatis依赖。在Maven项目中,可以在pom.xml文件中添加以下依赖:
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
</dependencies>
2. 配置文件
接下来,我们需要创建一个配置文件mybatis-config.xml,配置数据库连接信息以及MyBatis的运行环境:
<?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=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
3. 创建Mapper接口
创建一个Mapper接口,定义数据库操作的SQL语句:
package com.example.mapper;
import com.example.entity.User;
public interface UserMapper {
User getUserById(int id);
}
4. 创建Mapper XML
创建一个Mapper XML文件,定义具体的SQL语句:
<?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="getUserById" resultType="com.example.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
5. 测试
编写测试代码,测试MyBatis的功能:
package com.example;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisTest {
public static void main(String[] args) {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build("mybatis-config.xml");
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = userMapper.getUserById(1);
System.out.println(user);
}
}
}
使用技巧
1. 动态SQL
MyBatis支持动态SQL,可以方便地实现条件判断、循环等复杂SQL语句。
<select id="getUserList" resultType="com.example.entity.User">
SELECT * FROM user
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
2. 缓存
MyBatis提供了两种类型的缓存:一级缓存和二级缓存。一级缓存是SqlSession级别的缓存,二级缓存是Mapper级别的缓存。
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
3. 插件
MyBatis提供了插件机制,可以扩展MyBatis的功能。例如,我们可以使用插件来实现SQL执行时间监控。
public class SQLInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
long start = System.currentTimeMillis();
Object result = invocation.proceed();
long costTime = System.currentTimeMillis() - start;
System.out.println("SQL Execution Time: " + costTime + "ms");
return result;
}
}
实战案例
1. 基于MyBatis实现用户注册与登录
在这个案例中,我们将使用MyBatis实现用户注册与登录功能。
首先,创建User实体类:
package com.example.entity;
public class User {
private int id;
private String username;
private String password;
private int age;
// getters and setters
}
然后,创建UserMapper接口和XML文件:
package com.example.mapper;
import com.example.entity.User;
public interface UserMapper {
int register(User user);
User login(String username, String password);
}
<?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">
<insert id="register" parameterType="com.example.entity.User">
INSERT INTO user (username, password, age) VALUES (#{username}, #{password}, #{age})
</insert>
<select id="login" resultType="com.example.entity.User">
SELECT * FROM user WHERE username = #{username} AND password = #{password}
</select>
</mapper>
最后,编写测试代码:
package com.example;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUserTest {
public static void main(String[] args) {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build("mybatis-config.xml");
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = new User();
user.setUsername("test");
user.setPassword("123456");
user.setAge(20);
userMapper.register(user);
User login = userMapper.login("test", "123456");
System.out.println(login);
}
}
}
2. 基于MyBatis实现商品信息管理
在这个案例中,我们将使用MyBatis实现商品信息管理功能。
首先,创建Product实体类:
package com.example.entity;
public class Product {
private int id;
private String name;
private double price;
private int stock;
// getters and setters
}
然后,创建ProductMapper接口和XML文件:
package com.example.mapper;
import com.example.entity.Product;
public interface ProductMapper {
int addProduct(Product product);
Product getProductById(int id);
int updateProduct(Product product);
int deleteProduct(int id);
}
<?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.ProductMapper">
<insert id="addProduct" parameterType="com.example.entity.Product">
INSERT INTO product (name, price, stock) VALUES (#{name}, #{price}, #{stock})
</insert>
<select id="getProductById" resultType="com.example.entity.Product">
SELECT * FROM product WHERE id = #{id}
</select>
<update id="updateProduct" parameterType="com.example.entity.Product">
UPDATE product SET name = #{name}, price = #{price}, stock = #{stock} WHERE id = #{id}
</update>
<delete id="deleteProduct" parameterType="int">
DELETE FROM product WHERE id = #{id}
</delete>
</mapper>
最后,编写测试代码:
package com.example;
import com.example.entity.Product;
import com.example.mapper.ProductMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisProductTest {
public static void main(String[] args) {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build("mybatis-config.xml");
try (SqlSession session = sqlSessionFactory.openSession()) {
ProductMapper productMapper = session.getMapper(ProductMapper.class);
Product product = new Product();
product.setName("iPhone 12");
product.setPrice(7999.0);
product.setStock(100);
productMapper.addProduct(product);
Product productById = productMapper.getProductById(1);
System.out.println(productById);
productById.setPrice(8499.0);
productById.setStock(50);
productMapper.updateProduct(productById);
productMapper.deleteProduct(1);
}
}
}
通过以上案例,我们可以看到MyBatis在项目中的应用非常广泛。熟练掌握MyBatis的使用技巧,可以帮助我们更好地开发项目。
