浅谈MyBatis

一、Mybatis简介

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

1.1 引入依赖(pom.xml)

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
            <type>pom</type>
        </dependency>

1.2 全局配置文件(mybatis-config.xml)

<configuration>
    <properties>
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/activity?characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </properties>
    <!-- 环境,可以配置多个,default:指定采用哪个环境 -->
    <environments default="test">
        <!-- id:唯一标识 -->
        <environment id="test"/>
        <environment id="prot"/>
    </environments>
    <mappers>
        <mapper resource="mapper/map.xml" />
    </mappers>
</configuration>

1.3 配置map.xml(map.xml)

<!-- mapper:根标签,namespace:命名空间,随便写,一般保证命名空间唯一 -->
<mapper namespace="mapper">
    <!-- statement,内容:sql语句。id:唯一标识,随便写,在同一个命名空间下保持唯一
       resultType:sql语句查询结果集的封装类型需全路径,person即为数据库中的表-->
    <select id="selectUserById" resultType="...User">
            select * from person where id= #{id}
    </select>
    <select id="selectUserByName" resultType="...User">
        select * from person where name= #{name}
    </select>
</mapper>

1.4.修改全局配置文件(mybatis-config.xml)

<configuration>
    <!-- 添加加载map.xml配置文件 -->
    <mappers>
        <mapper resource="mapper/map.xml" />
    </mappers>
</configuration>

1.5 构建sqlSessionFactory 

Mybatis中3个重要的概念:Configuration(容器),SqlSessionFactory(工厂),SqlSession;

相对于Spring中的applicationContext,BeanFactory,Bean。不同之处在于SqlSession包含了所有的SQL方法,即这个SqlSession有且只有一个。SqlSession可以执行mybatis中注册的所有方法。

        // 指定全局配置文件
        String resource = "mybatis-config.xml";
        // 读取配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 构建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

1.6 打开sqlSession会话,并执行sql

        // 获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //<!-- SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。
        //你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。例如:-->
        try {
            // 操作CRUD,第一个参数:指定statement,规则:命名空间+“.”+statementId
            // 第二个参数:指定传入sql的参数:这里是用户id
            User user = sqlSession.selectOne("mapper.selectUserByName", "name");
            System.out.println(user);
        } finally {
            sqlSession.close();
        }

 1.7构建UserMapper 

public interface UserMapper {
    User selectUserById(Long id);
    User selectUserByName(String name);
    int  updateUser(User user);
}

<!-- 这里namespace必须是UserMapper接口的路径,不然要运行的时候要报错 “is not known to the MapperRegistry”-->
<mapper namespace="...UserMapper">
    <!-- statement,内容:sql语句。id:唯一标识,随便写,在同一个命名空间下保持唯一
       resultType:sql语句查询结果集的封装类型需全路径,person即为数据库中的表-->
    <select id="selectUserById" resultType="...User" parameterType="java.lang.Long">
            select * from person where id= #{id}
    </select>
    <select id="selectUserByName" resultType="...User" parameterType="java.lang.String">
        select * from person where name= #{name}
    </select>
    <!--更新用户信息-->
    <update id="updateUser" parameterType="...User">
        UPDATE person
        <set>
            <if test="name != null and name != ''">name=#{name},</if>
            <if test="sex >= 0">sex=#{sex},</if>
            <if test="age >= 0">sex=#{age},</if>
            <if test="height >= 0">height=#{height},</if>
            <if test="weight >= 0">weight=#{weight},</if>
        </set>
        WHERE id=#{id}
    </update>
</mapper>
          
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user= mapper.selectUserByName("name");
System.out.println(user);

2.1使用注解注入

接口必须添加@Mapper注解,注意,使用#符号和$符号的不同:

使用#{}意味着使用的预编译的语句,即在使用jdbc时的preparedStatement,sql语句中如果存在参数则会使用?作占位符,我们知道这种方式可以防止sql注入,并且在使用#{}时形成的sql语句,已经带有引号,例,select  * from table1 where id=#{id}  在调用这个语句时我们可以通过后台看到打印出的sql为:select * from table1 where id='2' 加入传的值为2.也就是说在组成sql语句的时候把参数默认为字符串。

使用${}时的sql不会当做字符串处理,是什么就是什么,如上边的语句:select * from table1 where id=${id} 在调用这个语句时控制台打印的为:select * from table1 where id=2 ,假设传的参数值为2

从上边的介绍可以看出这两种方式的区别,我们最好是能用#{}则用它,因为它可以防止sql注入,且是预编译的,在需要原样输出时才使用${},如,select * from ${tableName} order by ${id} 这里需要传入表名和按照哪个列进行排序 ,加入传入table1、id 则语句为:select * from table1 order by id如果是使用#{} 则变成了select * from 'table1' order by 'id' 我们知道这样就不对了。

@Mapper
public interface PersonMapper {

    @Select("Select * from person where name = #{name}")
    User selectTeachForGivenName(@Param("name") String name);

    @Select("Select * from person where name = '${name}'")
    User selectTeachLikeName(@Param("name") String name);

    @Select("select * from person")
    List<User> queryUser();

    @Select("SELECT * FROM users WHERE id = #{id}")
    User selectUserById(Long id);

    @Select("select * from person")
    User selectUserByName(@Param("name") String name);

}

 2.2执行测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisTest {

    @Autowired
    PersonMapper personMapper;
    @Test
    public void testMybatis(){
        List<User> users = personMapper.queryUser();
        System.out.println(users);
    }
}

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值