Third, the basic use of MyBatis-query

1. Introduction to SqlSessionFactory

  1. SqlSessionFactory is the core object of mybatis
  2. Used to initialize mybatis and create SqlSession object
  3. To ensure that SqlSessionFactory is globally unique in the application, we usually initialize it through static classes. The essence of SqlSessionFactory is to complete the initialization of the mybatis framework by loading configuration files.

2. Introduction to SqlSession

  1. SqlSession is the core object of mybatis operating database
  2. SqlSession uses jdbc to interact with the database. If it is not so rigorous, we can regard a SqlSession as an extended connection database connection object, which encapsulates a large number of practical methods on the basis of the original connection.
  3. The SqlSession object provides the CRUD corresponding method of the data table

Below we demonstrate the creation process of SqlSessionFactory and SqlSession, and by the way, we also verify whether the previous configuration is valid

/**
 * 初始化SqlSessionFactory并得到SqlSession对象
 */
public class SqlSessionFactoryTest {
    
    
    @Test
    public void test() throws IOException {
    
    
        // 利用Reader读取mybatis核心配置文件
        Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
        // 初始化SqlSessionFactory对象并进行配置文件解析
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        System.out.println("SqlSessionFactory加载成功");
        // 创建SqlSession对象,SqlSession是jdbc扩展类,用于和数据库进行交互
        SqlSession sqlSession = null;
        try {
    
    
            sqlSession = sqlSessionFactory.openSession();
            // 创建数据库连接的过程(这里只是测试使用,非必要,正常开发时是由mybatis帮我们自动完成的)
//            Connection connection = sqlSession.getConnection();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (sqlSession != null) {
    
    
                // 如果是“POOLED",代表使用连接池,close则是将连接回收到连接池中
                // 如果是“UNPOOLED",代表直连,close则会调用connection.close()方法
                sqlSession.close();
            }
        }
    }
}

If the configuration information is wrong, the system will report error
Insert picture description here
3.​Initialize the tool class MyBatisUtils

The main responsibility of the MyBatisUtils tool is to help us initialize the core object of SqlSessionFactory to ensure that the SqlSessionFactory is globally unique. We will demonstrate directly through the program

/**
 * MyBatisUtils工具类,创建全局唯一SqlSessionFactory对象
 */
public class MyBatisUtils {
    
    
    // 利用static属于类不属于对象,且全局唯一
    private static SqlSessionFactory sqlSessionFactory = null;
    // 利用静态块在初始化类时实例化sqlSessionFactory
    static {
    
    
        Reader reader = null;
        try {
    
    
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
    
    
            e.printStackTrace();
            // 初始化错误时抛出异常ExceptionInInitializerError通知调用者
            throw new ExceptionInInitializerError();
        }
    }

    //创建一个新的SqlSession对象
    public static SqlSession openSession() {
    
    
        return sqlSessionFactory.openSession();
    }

    //关闭SqlSession对象
    public static void closeSqlSession(SqlSession sqlSession) {
    
    
        if (sqlSession != null) {
    
    
            sqlSession.close();
        }
    }
}

Error prompt in case of error
Insert picture description here

Four, MyBatis data query

1. Create an entity class (Entity)

// 创建实体类
public class Goods {
    
    
    private int id;
    private String title;
    private String subTitle;
    private float originalCost;
    private float currentPrice;
    private float discount;
    private int isFreeDelivery;
    private int categoryId;

    public int getId() {
    
    
        return id;
    }

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

    public String getTitle() {
    
    
        return title;
    }

    public void setTitle(String title) {
    
    
        this.title = title;
    }

    public String getSubTitle() {
    
    
        return subTitle;
    }

    public void setSubTitle(String subTitle) {
    
    
        this.subTitle = subTitle;
    }

    public float getOriginalCost() {
    
    
        return originalCost;
    }

    public void setOriginalCost(float originalCost) {
    
    
        this.originalCost = originalCost;
    }

    public float getCurrentPrice() {
    
    
        return currentPrice;
    }

    public void setCurrentPrice(float currentPrice) {
    
    
        this.currentPrice = currentPrice;
    }

    public float getDiscount() {
    
    
        return discount;
    }

    public void setDiscount(float discount) {
    
    
        this.discount = discount;
    }

    public int getIsFreeDelivery() {
    
    
        return isFreeDelivery;
    }

    public void setIsFreeDelivery(int isFreeDelivery) {
    
    
        this.isFreeDelivery = isFreeDelivery;
    }

    public int getCategoryId() {
    
    
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
    
    
        this.categoryId = categoryId;
    }
}

2. Create Mapper XML: Explain which table the entity class and which table, attribute and which field in the table correspond to
3. Write sql tags and sql statements in 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 XML :说明实体类和哪个表,属性和表里哪个字段对应,当前SQL语句是什么-->
<!--namespace功能类似java中的包,不同的功能可以指定不同的namespace。
namespace名称必须是惟一的,
底下的id可以不是唯一,不同的namespace可以存在同名id-->
<mapper namespace="goods">
    <!--id功能相当于sql的别名-->
    <!--resultType表示数据查询出来后用什么对象保存记录-->
    <select id="selectAll" resultType="com.imooc.mybatis.entity.Goods">
        select * from t_goods order by goods_id desc limit 10
    </select>
</mapper>

4. Set the camel case naming mapping in the mabatis-config.xml configuration file
5. Add a new file declaration in the mabatis-config.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>
    <!--设置成支持驼峰命名-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!--默认环境配置-->
    <environments default="dev">
        <!--支持配置多套环境-->
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <!--采用连接池方式管理数据库连接-->
            <dataSource type="POOLED">
                <!--配置数据库连接信息-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql://localhost:3306/babytun?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false&amp;serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
        <environment id="prd">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql//192.168.0.1:3306/babytun?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false&amp;serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--声明goods.xml类,让mybatis认识这个文件-->
    <mappers>
        <mapper resource="mappers/goods.xml"/>
    </mappers>

</configuration>

6. Execute select statement in SqlSession

@Test
public void testSelectGoods(){
    
    
    SqlSession sqlSession = null;
    try {
    
    
        sqlSession = MyBatisUtils.openSession();
        // 进行查询,传入的参数取的是在goods.xml文件的namespace名称和select id
        List<Goods> list = sqlSession.selectList("goods.selectAll");
        for (Goods goods : list) {
    
    
            System.out.println(goods.getTitle());
        }
    } catch (Exception e) {
    
    
        throw e;
    } finally {
    
    
        MyBatisUtils.closeSqlSession(sqlSession);
    }
}

Five, SQL parameter transfer

  1. We call the situation where parameters need to be dynamically passed in as SQL parameter passing
  2. sql parameter transfer supports single parameter and multi-parameter query

1. Single parameter query
1) Add configuration data to the configuration table

<?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="goods">
    <!--传入单参数-->
    <select id="selectById" parameterType="int" resultType="com.imooc.mybatis.entity.Goods">
        select * from t_goods where goods_id=#{value }
    </select>
</mapper>

2) Writing query statements

@Test
public void testSelectById() {
    
    
    SqlSession sqlSession = null;
    try {
    
    
        sqlSession = MyBatisUtils.openSession();
        // 查询单个(第一个参数表示是要查询的对象,第二个表示要动态传递的参数
        Goods goods = sqlSession.selectOne("goods.selectById",739);
        System.out.println(goods.getTitle());
    } catch (Exception e) {
    
    
        throw e;
    } finally {
    
    
        MyBatisUtils.closeSqlSession(sqlSession);
    }
}

2. Multi-parameter query

1) Add configuration data in the configuration table

<?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="goods">
    <!--传递多参数,使用parameterType指定map接口,sql中的#{key}提取参数-->
    <select id="selectParams" parameterType="java.util.Map" resultType="com.imooc.mybatis.entity.Goods">
        select * from t_goods
         where current_price between #{min} and #{max }
          order by current_price
          limit 0,#{limt}
    </select>
</mapper>

2) Writing query statements

// 多参数查询
    @Test
    public void testSelectParams() {
    
    
        SqlSession sqlSession = null;
        try {
    
    
            sqlSession = MyBatisUtils.openSession();
            // 配置xml文件里的所有值都需要传入
            Map map = new HashMap();
            map.put("min", 100);
            map.put("max", 200);
            map.put("limt", 10);
            List<Goods> list = sqlSession.selectList("goods.selectParams", map);
            for (Goods lists : list) {
    
    
                System.out.println(lists.getTitle() + ":" + lists.getCurrentPrice());
            }

        } catch (Exception e) {
    
    
            throw e;
        } finally {
    
    
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }

Six, get the results of multi-table related query

  1. Before configuring the xml file in the multi-table query, the map type used by the resultType, the result is out of order. So it is more recommended to use LinkedHashMap.
  2. When using LinkedHashMap, Mybatis will package each record as a LinkedHashMap object, the key is the field name, the value is the value corresponding to the field, and the field type is automatically judged according to the table structure.
    Advantages: easy to expand and easy to use. Disadvantages: too flexible to be checked at compile time
  3. The result of the query here is also the original field name, and is no longer the case-inclusive name of the entity
  4. The specific configuration is as follows
<?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="goods">
    <select id="selectByMap" resultType="java.util.LinkedHashMap">
        select * from t_goods g,t_category c where g.category_id=c.category_id;
    </select>
</mapper>
@Test
public void testSelectByMap() {
    
    
    SqlSession sqlSession = null;
    try {
    
    
        sqlSession = MyBatisUtils.openSession();
        List<Map> list = sqlSession.selectList("goods.selectByMap");
        for (Map map : list) {
    
    
            System.out.println(map);
        }
    } catch (Exception e) {
    
    
        throw e;
    } finally {
    
    
        MyBatisUtils.closeSqlSession(sqlSession);
    }
}

Guess you like

Origin blog.csdn.net/qq_36792120/article/details/112130562