SpringBoot整合Mybaits入门

SpringBoot整合Mybaits入门

导入mybaits,mysql 驱动 依赖

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

            <!-- 使用JDBC链接mysql的驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.19</version>
            </dependency>

在resource文件目录下,新建一个config文件目录,用于存放我们所写的各种config文件,新建一个mybatis.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://127.0.0.1:3306/xdclass?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers><!--- 注册自己写的Mapper.xml -->

        <mapper resource="mapper/VideoMapper.xml"/>
    </mappers>
</configuration>

再在resource目录新建一个Mapper目录用于存放我们所写的各种Mapper.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.test.dao.ViedoMapper">
    <select id="selectById" resultType="com.example.test.domain.Video">
    select * from video where id = #{video_id}
   </select>

</mapper>

在dao层,新建对应的Mapper接口

//数据库交互层
public interface VideoMapper {
    Video selectById(@Param("video_id") int videoId);//通过注解方式实现,此种方式我们需要去写一个xml

    @Select("select * from video")//直接通过注解实现,加了注解就不会去找xml了
    List<Video>selectlist();

}


在domain层中写我们与数据库表对应的JavaBean

main函数

    public static void main(String[] args) throws IOException {

        //SpringApplication.run(TestApplication.class, args);
        String resouce = "config/mybatis-config.xml";

        //读取配置文件
        InputStream inputStream =  Resources.getResourceAsStream(resouce);

        //构建Session工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //获取Session
        try(SqlSession sqlSession = sqlSessionFactory.openSession()){

            VideoMapper videoMapper = sqlSession.getMapper(VideoMapper.class);

            Video video = videoMapper.selectById(2);

            System.out.println(video.toString());



        }
    }

总体结构如下

SpringBoot整合Mybaits入门
完成

上一篇:MyBaits系列(三)MyBatis的模糊查询和SQL注入


下一篇:MyBaits入门完结篇