Mybatis1

一、Mybatis使用

Mybatis官方文档网站:https://mybatis.org/mybatis-3/zh/getting-started.html

1.导入jar

 <!--        mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <!--        mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.4</version>
        </dependency>

2.编写实体类和Dao接口

实体类:

public class Book {
    private int id;
    private String name;
    private BigDecimal price;
    private String author;
    private int sales;
    private int stock;
    private String img_path = "imgs/1.jpg";

    public Book() {
    }

    public Book(int id, String name, BigDecimal price, String author, int sales, int stock,String img_path) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.author = author;
        this.sales = sales;
        this.stock = stock;
        this.img_path = img_path;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public int getSales() {
        return sales;
    }

    public void setSales(int sales) {
        this.sales = sales;
    }

    public int getStock() {
        return stock;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", author='" + author + '\'' +
                ", sales=" + sales +
                ", stock=" + stock +
                ", img_path='" + img_path + '\'' +
                '}';
    }
}

Dao接口:

import bean.Book;
import java.util.List;

public interface BookDao {
    public List<Book> getBookList();
}

3.编写DaoMapper.xml文件,mapper映射器

(可看作Dao实现类)

<?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">
    
<!--绑定一个对应的Dao/Map接口-->
<!--namespace是用来绑定对应的接口,是必写的-->
<mapper namespace="dao.BookDao">
    
<!--    查询语句-->
    <select id="getBookList" resultType="bean.Book">
        select * from t_book;
    </select>

</mapper>

4.编写Mybatis-config.xm核心配置文件

<?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">
<!-- mybatis核心配置文件 -->

<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:3308/store?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

<!--    每个Mapper.xml都需要在Mybatis-->
    <mappers>
        <mapper resource="dao/BookMapper.xml"/>
    </mappers>

</configuration>

5.编写Mybatis工具类

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;

// SqlSessionFactory -->  SqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 由mybatis—config.xml 得到SqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 使用Mybatis重要的一步 , 获取SqlSession对象
    public static SqlSession getSqlSession() {
        // 优化
        return sqlSessionFactory.openSession();
    }
}

6.编写测试

import bean.Book;
import dao.BookDao;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import utils.MybatisUtils;
import java.util.List;

public class BookDaoTest {
    @Test
    public void Test01() {
        SqlSession sqlSession = null;
        try {
            // 1. 获取sqlSession对象
            sqlSession = MybatisUtils.getSqlSession();
            // 2. 执行sql语句(常用的getMapper(接口.class))
            BookDao mapper = sqlSession.getMapper(BookDao.class);
            List<Book> bookList = mapper.getBookList();

 // 不常用 .selectOne(对应的全接口名中的方法名)/.selectList(同上)/.selectMap(同上)
 // List<Book> bookList = sqlSession.selectList("dao.BookDao.getBookList");
            
            for (Book book : bookList) {
                System.out.println(book);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }
}

7.注意

如果在Maven中使用Mybatis,还注意需要在pom.xml中加入以下代码

<!--    在build中配置resource,防止资源导出失败-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

SqlSession中的注意点
Mybatis1

上一篇:Command Sequence-题解


下一篇:素数筛选法(埃氏筛 欧拉筛)