创建一个简单的mybatis项目

  1. 构建maven项目
  2. 导入mybatis和jdbc依赖
<dependency>
    <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <version>8.0.11</version>
 </dependency>
 <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
 <dependency>
     <groupId>org.mybatis</groupId>
     <artifactId>mybatis</artifactId>
     <version>3.5.3</version>
 </dependency>
  1. 在resource 下创建generatorConfig.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>
    <!--   配置环境-->
    <properties resource="db.properties"></properties>
    <environments default="mysql">
        <!--配置mysql的环境-->
        <environment id="mysql">
            <!--配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置连接池-->
            <dataSource type="POOLED">
                <!--配置连接数据库的4个基本信息-->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--这下面添加mapper-->
    
</configuration>
  1. 同时在resource下创建db.properties文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
jdbc.username=root
jdbc.password=dexuan97
  1. 在mysql中创建一个test数据库,创建一个user表
    在这里插入图片描述
  2. 创建一个User类,作为表到对象的映射。
public class User {
    private int userId;
    private String name;
    private String password;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
  1. 创建UserMapper接口
@Mapper
public interface UserMapper {
    @Select("select * from user where user_id = #{id}")
    @Results(id="getUserById",value = {
            @Result(property="userId",column="user_id"),
            @Result(property="name",column="username"),
            @Result(property="password",column="password")
    })

    List<User> getUserById(@Param("id") int id);
}
}
  1. 在resource下新建mapper,mapper中新建User.xml代表UserMapper接口的配置文件
<?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">
<!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 -->
<mapper namespace="mapper.UserMapper">

</mapper>
  1. 在全局配置配置中添加User.xml的定位
<!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
 <mappers>
     <mapper resource="mapper/User.xml" />
 </mappers>
  1. 添加主运行程序App.java并运行
public class App {
    /***
     * 1. 创建一个sqlSessionFactory
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
         //创建一个sqlSessionFactory
         String resource = "generatorConfig.xml";
         InputStream inputStream = Resources.getResourceAsStream(resource);
         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
         //从工厂中获取sqlSession实例
        SqlSession openSession=sqlSessionFactory.openSession();
        UserMapper userMapper=openSession.getMapper(UserMapper.class);
        List<User> user=userMapper.getUserById(1);
        System.out.println(user);

    }
}
Logo

更多推荐