使用IDEA创建Mybatis项目

作者:carzy2024.01.17 09:41浏览量:65

简介:本文将详细介绍如何使用IntelliJ IDEA创建Mybatis项目,包括创建项目、添加依赖、配置Mybatis等步骤。

千帆应用开发平台“智能体Pro”全新上线 限时免费体验

面向慢思考场景,支持低代码配置的方式创建“智能体Pro”应用

立即体验

首先,我们需要在IntelliJ IDEA中创建一个新的项目。在菜单栏中选择File -> New -> Project...
在弹出的对话框中,选择Java项目,然后点击Next
在接下来的页面中,你可以设置项目的名称、位置和JDK版本,然后点击Finish
接下来,我们需要添加Mybatis的依赖。在项目结构视图中,右键点击pom.xml文件,选择Add -> Library -> From Maven...
在弹出的对话框中,输入Mybatis的依赖项,然后点击OK
现在,我们需要在IDEA中配置Mybatis。右键点击项目的资源文件夹(通常为src/main/resources),选择New -> File,然后输入文件名mybatis-config.xml
在打开的新文件中,输入Mybatis的配置信息,例如数据源和映射文件的路径等。以下是一个简单的例子:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd>
  3. <configuration>
  4. <environments default="development">
  5. <environment id="development">
  6. <transactionManager type="JDBC"/>
  7. <dataSource type="POOLED">
  8. <property name="driver" value="com.mysql.jdbc.Driver"/>
  9. <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
  10. <property name="username" value="root"/>
  11. <property name="password" value="password"/>
  12. </dataSource>
  13. </environment>
  14. </environments>
  15. <mappers>
  16. <mapper resource="com/example/mappers/ExampleMapper.xml"/>
  17. </mappers>
  18. </configuration>

请根据你的实际情况修改数据库连接信息。
现在,我们需要在Java代码中使用Mybatis。首先,我们需要创建一个ExampleMapper接口,然后创建一个ExampleMapper.xml映射文件,最后在Java代码中注入SqlSession并调用ExampleMapper的方法。以下是一个简单的例子:
Java代码:

  1. public interface ExampleMapper {
  2. Example getExampleById(int id);
  3. }

ExampleMapper.xml映射文件:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd>
  3. <mapper namespace="com.example.mappers.ExampleMapper">
  4. <select id="getExampleById" parameterType="int" resultType="com.example.models.Example">
  5. SELECT * FROM example WHERE id = #{id}
  6. </select>
  7. </mapper>

在Java代码中注入SqlSession并调用ExampleMapper的方法:

  1. SqlSession session = sqlSessionFactory.openSession();
  2. ExampleMapper mapper = session.getMapper(ExampleMapper.class);
  3. Example example = mapper.getExampleById(1);
  4. session.close();

以上就是使用IntelliJ IDEA创建Mybatis项目的步骤。如果你需要更深入的了解Mybatis的使用,可以参考Mybatis的官方文档

article bottom image

相关文章推荐

发表评论