本文目录导读:

我来详细介绍Java MyBatis映射的配置案例,包括XML和注解两种方式。
基础依赖配置
Maven依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
MyBatis主配置文件
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?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<!-- 注册映射文件 -->
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
<mapper class="com.example.mapper.UserMapper"/>
</mappers>
</configuration>
实体类与数据库表
数据库表结构
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`order_no` varchar(50) DEFAULT NULL,
`total_amount` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
实体类
// User.java
public class User {
private Integer id;
private String username;
private String password;
private String email;
private Date createTime;
private List<Order> orders; // 一对多关联
// getter和setter方法
}
// Order.java
public class Order {
private Integer id;
private Integer userId;
private String orderNo;
private BigDecimal totalAmount;
private User user; // 多对一关联
// getter和setter方法
}
XML映射配置
基础CRUD映射
<!-- 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="userMap" type="com.example.entity.User">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="email" column="email"/>
<result property="createTime" column="create_time"/>
</resultMap>
<!-- 查询所有用户 -->
<select id="findAll" resultMap="userMap">
SELECT * FROM user
</select>
<!-- 根据ID查询 -->
<select id="findById" resultMap="userMap" parameterType="int">
SELECT * FROM user WHERE id = #{id}
</select>
<!-- 插入用户 -->
<insert id="insert" parameterType="com.example.entity.User"
useGeneratedKeys="true" keyProperty="id">
INSERT INTO user(username, password, email, create_time)
VALUES(#{username}, #{password}, #{email}, #{createTime})
</insert>
<!-- 更新用户 -->
<update id="update" parameterType="com.example.entity.User">
UPDATE user
SET username = #{username},
password = #{password},
email = #{email}
WHERE id = #{id}
</update>
<!-- 删除用户 -->
<delete id="deleteById" parameterType="int">
DELETE FROM user WHERE id = #{id}
</delete>
<!-- 动态SQL查询 -->
<select id="findByCondition" resultMap="userMap"
parameterType="com.example.entity.User">
SELECT * FROM user
<where>
<if test="username != null and username != ''">
AND username LIKE CONCAT('%', #{username}, '%')
</if>
<if test="email != null and email != ''">
AND email = #{email}
</if>
</where>
</select>
</mapper>
关联映射配置
一对多关联(User -> Order)
<!-- UserMapper.xml中的关联映射 -->
<resultMap id="userWithOrdersMap" type="com.example.entity.User">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="email" column="email"/>
<result property="createTime" column="create_time"/>
<!-- 一对多关联映射 -->
<collection property="orders" ofType="com.example.entity.Order">
<id property="id" column="order_id"/>
<result property="orderNo" column="order_no"/>
<result property="totalAmount" column="total_amount"/>
</collection>
</resultMap>
<!-- 连表查询 -->
<select id="findUserWithOrders" resultMap="userWithOrdersMap">
SELECT u.*, o.id as order_id, o.order_no, o.total_amount
FROM user u
LEFT JOIN `order` o ON u.id = o.user_id
WHERE u.id = #{id}
</select>
多对一关联(Order -> User)
<!-- OrderMapper.xml中的关联映射 -->
<resultMap id="orderWithUserMap" type="com.example.entity.Order">
<id property="id" column="id"/>
<result property="userId" column="user_id"/>
<result property="orderNo" column="order_no"/>
<result property="totalAmount" column="total_amount"/>
<!-- 多对一关联映射 -->
<association property="user" javaType="com.example.entity.User">
<id property="id" column="user_id"/>
<result property="username" column="username"/>
<result property="email" column="email"/>
</association>
</resultMap>
<select id="findOrderWithUser" resultMap="orderWithUserMap">
SELECT o.*, u.username, u.email
FROM `order` o
JOIN user u ON o.user_id = u.id
WHERE o.id = #{id}
</select>
注解映射配置
// UserMapper.java 使用注解
public interface UserMapper {
@Select("SELECT * FROM user")
@Results(id = "userMap", value = {
@Result(property = "id", column = "id", id = true),
@Result(property = "username", column = "username"),
@Result(property = "password", column = "password"),
@Result(property = "email", column = "email"),
@Result(property = "createTime", column = "create_time")
})
List<User> findAll();
@Select("SELECT * FROM user WHERE id = #{id}")
@ResultMap("userMap")
User findById(int id);
@Insert("INSERT INTO user(username, password, email, create_time) " +
"VALUES(#{username}, #{password}, #{email}, #{createTime})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insert(User user);
@Update("UPDATE user SET username=#{username}, password=#{password}, " +
"email=#{email} WHERE id=#{id}")
int update(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
int deleteById(int id);
// 动态SQL使用脚本
@Select("<script>" +
"SELECT * FROM user" +
"<where>" +
"<if test='username != null and username != \"\"'>" +
"AND username LIKE CONCAT('%', #{username}, '%')" +
"</if>" +
"</where>" +
"</script>")
List<User> findByCondition(User user);
}
Spring Boot集成配置
# application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/mybatis_db?useSSL=false&serverTimezone=UTC
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.entity
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
使用示例
// 测试代码
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testCRUD() {
// 插入
User user = new User();
user.setUsername("testuser");
user.setPassword("123456");
user.setEmail("test@example.com");
user.setCreateTime(new Date());
userMapper.insert(user);
// 查询
User foundUser = userMapper.findById(user.getId());
System.out.println(foundUser.getUsername());
// 更新
foundUser.setEmail("newemail@example.com");
userMapper.update(foundUser);
// 删除
userMapper.deleteById(foundUser.getId());
}
}
- 命名空间:XML映射文件的namespace必须与Mapper接口全限定名一致
- 结果映射:数据库字段名和Java属性名不一致时使用resultMap
- 参数传递:使用进行预编译参数,进行字符串替换
- 主键回填:插入操作使用
useGeneratedKeys获取自增主键 - 关联映射:使用
association(一对一)和collection(一对多)处理关联关系 - 动态SQL:使用
<if>、<where>、<foreach>等标签构建动态查询
这个案例覆盖了MyBatis映射的常见配置场景,可以作为实际项目的参考模板。
版权声明:足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播