mybatis-plus对数据库操作介绍以及简单的连表查询数据

MyBatis是一种持久层框架,它可以帮助我们轻松地管理数据库操作。以下是MyBatis的详细介绍。

一、mybatis-plus介绍

1.安装

MyBatis可以使用Maven进行依赖管理。在pom.xml文件中添加以下依赖:

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.7</version>
</dependency>

2.配置

在使用MyBatis之前,我们需要对其进行配置。我们可以使用XML配置文件或Java代码进行配置。

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.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  <!-- 映射文件 -->
  <mappers>
    <mapper resource="com/example/mapper/UserMapper.xml"/>
  </mappers>
</configuration>

在此配置文件中,指定了数据库连接信息和映射文件的位置。

Java代码配置

下面是一个使用Java代码配置MyBatis的代码:

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
  @Bean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    factoryBean.setDataSource(dataSource);
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    factoryBean.setMapperLocations(resolver.getResources("classpath*:com/example/mapper/*.xml"));
    return factoryBean.getObject();
  }
}

上面,使用Spring框架的@Configuration注解来标识这是一个配置类,在其中创建SqlSessionFactory

二、注解

MyBatis提供了许多注解,可以帮助我们快速完成数据库操作。以下是常用的注解:

  • @Select:查询数据。
  • @Insert:插入数据。
  • @Update:更新数据。
  • @Delete:删除数据。
  • @ResultMap:定义映射关系。

查询数据

以下是使用MyBatis注解查询数据的代码:

@Mapper
public interface UserMapper {
  @Select("SELECT * FROM users WHERE id = #{id}")
  User findById(@Param("id") Long id);
}

上面,使用@Select注解来执行SELECT语句,并使用#{ id}占位符来传递参数。

插入数据

下面是使用MyBatis注解插入数据的代码:

@Mapper
public interface UserMapper {
  @Insert("INSERT INTO users(name, age) VALUES(#{name}, #{age})")
  @Options(useGeneratedKeys = true, keyProperty = "id")
  int insert(User user);
}

上面,使用@Insert注解来执行INSERT语句,并使用#{ name}#{ age}占位符来插入数据。@Options注解可以用于指定自动生成的键,这里我们使用useGeneratedKeys属性来开启自动生成,使用keyProperty属性来指定自动生成的键对应的实体属性。

更新数据

使用MyBatis注解更新数据的代码

@Mapper
public interface UserMapper {
  @Update("UPDATE users SET name = #{name}, age = #{age} WHERE id = #{id}")
  int update(User user);
}

上面,使用@Update注解来执行UPDATE语句,并使用#{name}#{age}#{id}占位符来更新数据。

删除数据

以下是使用MyBatis注解删除数据的示例:

@Mapper
public interface UserMapper {
  @Delete("DELETE FROM users WHERE id = #{id}")
  int deleteById(@Param("id") Long id);
}

上面使用@Delete注解来执行DELETE语句,并使用#{id}占位符来删除指定ID的数据。

三、操作数据库

除了使用注解之外,还可以通过XML映射文件来操作数据库。以下是一个使用XML映射文件查询用户信息的示例:

映射文件

<!-- 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">
  <select id="findById" resultType="com.example.entity.User">
    SELECT * FROM users WHERE id = #{id}
  </select>
</mapper>

上面定义了一个<select>标签来执行SELECT语句,并使用resultType属性来指定返回结果的实体类。

Java代码

public class UserMapperImpl implements UserMapper {
  private final SqlSession sqlSession;

  public UserMapperImpl(SqlSession sqlSession) {
    this.sqlSession = sqlSession;
  }

  public User findById(Long id) {
    return sqlSession.selectOne("com.example.mapper.UserMapper.findById", id);
  }
}

上面创建了一个UserMapperImpl类来实现UserMapper接口,并在构造函数中传入了一个SqlSession对象,用于执行SQL语句。

使用MyBatis进行数据库操作的一般流程如下:

  1. 配置MyBatis。
  2. 定义映射文件或注解。
  3. 获取SqlSessionFactory实例。
  4. 获取SqlSession实例。
  5. 执行SQL语句。

代码如下:

public class UserService {
  private final SqlSessionFactory sqlSessionFactory;

  public UserService(SqlSessionFactory sqlSessionFactory) {
    this.sqlSessionFactory = sqlSessionFactory;
  }

  public User findById(Long id) {
    try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
      UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      return userMapper.findById(id);
    }
  }

  public int save(User user) {
    try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
      UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      return userMapper.insert(user);
    }
  }

  public int update(User user) {
    try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
      UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      return userMapper.update(user);
    }
  }

  public int deleteById(Long id) {
    try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
      UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      return userMapper.deleteById(id);
    }
  }
}

上面定义了一个UserService类来使用MyBatis进行数据库操作,其中包括根据ID查询用户信息、保存用户信息、更新用户信息和删除用户信息四个方法。

二、在Spring Boot框架中使用MyBatis Plus进行连表查询

首先,在pom.xml文件中添加MyBatis Plus和相关依赖:确认数据库已经设置好,创建两个实体类User和Order,分别对应user表和order表:

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
}

@Data
public class Order {
    private Long id;
    private BigDecimal amount;
    private LocalDateTime createTime;
    private Long userId;
}

创建对应的Mapper接口UserMapper和OrderMapper,并继承BaseMapper类:

public interface UserMapper extends BaseMapper<User> {}

public interface OrderMapper extends BaseMapper<Order> {}

在配置文件application.yml中配置MyBatis Plus:

mybatis-plus:
  mapper-locations: classpath:mapper/*.xml # 配置mapper文件的位置
  configuration:
    map-underscore-to-camel-case: true # 开启驼峰命名转换

编写SQL语句,实现连表查询,例如查找用户及其所有订单的信息:

<select id="getUserAndOrdersById" resultMap="userResultMap">
    SELECT u.*, o.id as order_id, o.amount, o.create_time
    FROM user u
    LEFT JOIN `order` o ON u.id = o.user_id
    WHERE u.id = #{id}
</select>

<resultMap id="userResultMap" type="com.example.demo.entity.User">
    <id column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="age" property="age"/>
    <collection property="orders" ofType="com.example.demo.entity.Order">
        <id column="order_id" property="id"/>
        <result column="amount" property="amount"/>
        <result column="create_time" property="createTime"/>
    </collection>
</resultMap>

在对应的Mapper接口中使用@Select注解,指定SQL语句的id和参数:

@Select("getUserAndOrdersById")
@Results(id = "userResultMap", value = {
    @Result(property = "id", column = "id"),
    @Result(property = "name", column = "name"),
    @Result(property = "age", column = "age"),
    @Result(property = "orders", column = "id",
            many = @Many(select = "com.example.demo.mapper.OrderMapper.selectListByUserId"))
})
User getUserAndOrdersById(@Param("id") Long id);

在OrderMapper接口中实现子查询的方法:

@Select("SELECT * FROM `order` WHERE user_id = #{userId}")
List<Order> selectListByUserId(@Param("userId") Long userId);

这样就完成了在Spring Boot框架中使用MyBatis Plus进行连表查询的操作。

猜你喜欢

转载自blog.csdn.net/weixin_59367964/article/details/130609918