欢迎访问宙启技术站
智能推送

SpringBoot集成怎么使用MyBatis配置XML文件

发布时间:2023-05-16 10:04:00

MyBatis是一个优秀的持久化框架,目前广泛应用于JavaWeb开发中。SpringBoot是一个快速开发框架,也广泛应用于JavaWeb项目中。在SpringBoot项目中使用MyBatis可以更快地开发JavaWeb项目。下面介绍一下如何在SpringBoot项目中使用MyBatis配置XML文件。

步:创建SpringBoot项目

首先需要创建一个SpringBoot项目。使用IDEA或Eclipse等Java开发工具创建SpringBoot项目。可以选择SpringInitializer或手动创建。具体可以参考SpringBoot官方文档。

第二步:添加MyBatis和MyBatis-SpringBoot-Starter依赖

在pom.xml文件中添加以下依赖:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
</dependency>

这里使用的是MyBatis和MyBatis-SpringBoot-Starter的最新版本。

第三步:配置数据库连接信息

在application.yml或application.properties文件中配置数据库连接信息,例如:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456

这里以MySQL为例,配置了数据库驱动、数据库连接地址、用户名和密码等信息。

第四步:配置Mapper文件和实体类

在resources目录下创建mapper目录,在mapper目录下添加Mapper的xml文件,例如UserMapper.xml文件,用于编写SQL语句。同时在mapper目录下创建实体类对应的Java文件,例如User.java文件。

UserMapper.xml文件示例:

<mapper namespace="com.example.mapper.UserMapper">
  <select id="findById" resultType="java.lang.Integer" parameterType="java.lang.Integer">
    select * from user where id = #{id}
  </select>
  <select id="findAll" resultType="com.example.entity.User">
    select * from user
  </select>
</mapper>

User.java文件示例:

public class User {
    private Integer id;
    private String username;
    private String password;
    // getter和setter方法省略
}

需要注意的是,在UserMapper.xml文件中的namespace属性要填写完整的Mapper所在的包名和类名,可以避免出现命名冲突的问题。

第五步:扫描Mapper接口和Mapper文件

在启动类中添加注解@MapperScan,扫描Mapper接口和Mapper文件。

@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

这里的com.example.mapper为Mapper接口和Mapper文件所在的包名。

第六步:使用Mapper接口进行数据库操作

在需要进行数据库操作的类中,使用@Autowired注解注入Mapper接口。然后调用Mapper接口中的方法即可进行数据库操作。

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User findById(Integer id) {
        return userMapper.findById(id);
    }

    public List<User> findAll() {
        return userMapper.findAll();
    }
}

以上代码示例中,把UserMapper注入到UserService中,在UserService中调用UserMapper中的方法,即可实现数据库操作。

至此,以上就是使用SpringBoot集成MyBatis配置XML文件的详细步骤。如有不懂之处,可以参考SpringBoot官方文档或MyBatis官方文档。注意配置一定要正确,才能顺利使用MyBatis。