MyBatis的使用

39 阅读2分钟

1.MyBatis的配置文件

<!-- 配置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为根标签-->
<configuration>
(需改成自己的properties文件) <!--  读取properties配置文件,并解析,存储到内存中-->
    <properties resource="db.properties"></properties>
    <!--设置项 -->
    <settings>
        <!-- 输出日志-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
<!--    类型别名-->
    <typeAliases>
<!--        设置类型别名 type表示对象类型   alias表示别名名称-->
<!--        当前项目中所有的映射文件阿红,用到User对象,都是可以用别名的,并且大小写不区分-->
<!--        <typeAlias type="com.ruoxuan.entity.User" alias="User"></typeAlias>-->
<!--        配置指定包下所有的类都可以使用别名(在映射文件中),别名就是类别名称,并且不区分大小写-->
        包名换成自己的
        <package name="com.ruoxuan.entity"/>
    </typeAliases>
    <!--配置环境,可以配置多个-->
    <environments default="dev">

        <!--具体环境-->
        <environment id="dev">
            <!--事务管理器(JDBC)-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 数据源(使用连接池)-->
            <dataSource type="POOLED">
<!--                通过${配置文件中的key}方式读取对应配置文件中的值-->
                <!--数据库的驱动-->
                <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>


        <!--&gt;        <environment id="pro">-->
        <!--        <transactionManager type=""></transactionManager>-->
        <!--        <dataSource type=""></dataSource>-->
        <!--    </environment-->
    </environments>
    <!--使用映射文件-->
    <mappers>
        <!-- 使用resource资源方式引入映射文件,文件目录之间用斜杠分隔-->
        <mapper resource="mapper/UserMapper.xml"></mapper>
    </mappers>
</configuration>

2.使用mybatis进行查询需要创建SqlSession对象

2.1创建mapper接口的映射文件
<?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是全限定类名,要等于mapper接口 -->
<mapper namespace="com.ruoxuan.dao.UserMapper">
    
</mapper>

映射文件的规范

image.png **映射文件的插件 MyBatisX **

2.2创建SqlSession对象
public static SqlSession getSqlSession(){
   //创建SqlSessionFactoryBuilder对象
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
    //创建SqlSessionFactory对象
    SqlSessionFactory sqlSessionFactory= null;
    try {
        sqlSessionFactory =  sqlSessionFactoryBuilder.build(Resources.getResourceAsReader("mybatis.xml"));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    //创建SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    return sqlSession;
}
2.3利用SqlSession对象加载mapper接口并调用方法
@Test
public  void testSelectAll2(){
    SqlSession sqlSession = SqlSessionUtils.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User user=new User();
    user.setUsername("祝大哥");
    List<User> users=userMapper.selectAll2(user);
    System.out.println(users);
    sqlSession.close();
}

3.Mybatis

3.1Mybatis与Spring的资源配置
#驱动类名称
spring.datasource.driver-class-name=com.mysgl.cjjdbc.Driver
MysQL Dri噬荡verMysQL JDBC and R2DBC driver.Guide >Added dependencies:xMyBatis FrameworkxMySQL Driver
#数据库连接的url
spring.datasource.url=jdbc:mysgl://localhost:3306/mybatis
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=1234
#指定mybatis输出日志的位置,输出控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutlmpl
#开启驼峰命名自动映射,即从数据库字段名a column 映射到Java 属性名aColumn。必须符合规范
mvbatis.confiquration.map-underscore-to-camel-case=true

image.png

3.2配置SQL提示

image.png

image.png

4.Mybatis的动态SQL

4.1 if  where  set   trim     choose..when...other

image.png

image.png

image.png

image.png

使用choose when other

<!--相当于if  else if   else-->
<select id="selectAll1" resultType="user">
    select * from user where 1=1
    <choose>
        <when test="username!=null and username!=''">
            and username=#{username}
        </when>
        <when test="password!=null and password!=''">
            and password=#{password}
        </when>
        <otherwise>
            and 2=2
        </otherwise>
    </choose>


</select>