Mybatis入门

1.Mybatis相关概念

MyBatis 是支持普通SQL查询、存储过程和高级映射的优秀持久层框架。
Mybatis使用简单的XML或注解用于配置和原始映射,将接口和java的POJO(Plain Old Java Objects)映射成数据库的记录。

2.Mybatis工作流程

(1)加载配置
加载mybatis-config.xml
生成SqlSessionFactory
(2)解析sql
(3)执行sql返回结果集
(4)结果映射

3.搭建并使用Mybatis框架

(1)导入jar包

mybatis-3.4.0.jar
mysql-connector-java-5.1.47.jar

(2)配置文件

<?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="test">
        <!--配置数据库环境 -->
        <environment id="test">
            <transactionManager type="jdbc" />
            <dataSource type="POOLED">
                <property name="url" value="jdbc:mysql://localhost:3306/jw_chapter6"/>
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="cn/goktech/dao/UserMapper.xml" />
    </mappers>
</configuration>

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指定对应的DAO -->
<mapper namespace="cn.goktech.dao.UserDao">
    <!--id指定方法名,parameterType参数类型,resultType返回结果类型,返回类型要写全路径 -->
    <select id="getById" parameterType="Integer" resultType="cn.goktech.entity.User">
        select * from user where id=#{id}
    </select>

    <!--返回List时,写其泛型 -->
    <select id="getAll" resultType="cn.goktech.entity.User">
        select * from user
    </select>

    <update id="updateUser" parameterType="cn.goktech.entity.User" >
        update user set name=#{name},info=#{info} where id=#{id}
    </update>

    <select id="getOne" parameterType="int" resultType="Map">
        select * from user where id=#{id}
    </select>
    <!--resultMap给定映射关系 (针对字段名与属性不同,从而不能自动封装的情况)-->
    <select id="getOneById" parameterType="int" resultMap="userMap">
        select * from user where id=#{id}
    </select>
    <resultMap id="userMap" type="cn.goktech.entity.User">
        <!--id标签指定主键,column-数据库字段名,property-类的属性名 -->
        <id column="id" property="id" />
        <result column="name" property="name"/>
        <result column="age" property="age"/>
        <result column="phone" property="phone"/>
        <result column="info" property="info"/>
    </resultMap>

    <select id="getByName" parameterType="String" resultMap="userMap">
     <!-- #{}取值时会自动拼上双引号,${}不会,${}一般主要是用于引入数据库对象 -->
        <!--    select * from user where name  like concat('%',#{name},'%') -->
         select * from user where name  like '%${name}%'
    </select>
</mapper>

(3)DAO+Mapper.xml

UserDao

public interface UserDao {
    public List<User> getAll();

    public User getById(int id);

    public int updateUser(User user);//更新时不止一个字段,传一个类类型就可以了

    public Map<String,Object> getOne(int id);

    public User getOneById(int id);//映射

    //@Param指定参数名
//    public List<User> getByName(String name);
    public List<User> getByName(@Param("name") String name);

}

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指定对应的DAO -->
<mapper namespace="cn.goktech.dao.UserDao">
    <!--id指定方法名,parameterType参数类型,resultType返回结果类型,返回类型要写全路径 -->
    <select id="getById" parameterType="Integer" resultType="cn.goktech.entity.User">
        select * from user where id=#{id}
    </select>

    <!--返回List时,写其泛型 -->
    <select id="getAll" resultType="cn.goktech.entity.User">
        select * from user
    </select>

    <update id="updateUser" parameterType="cn.goktech.entity.User" >
        update user set name=#{name},info=#{info} where id=#{id}
    </update>

    <select id="getOne" parameterType="int" resultType="Map">
        select * from user where id=#{id}
    </select>
    <!--resultMap给定映射关系 (针对字段名与属性不同,从而不能自动封装的情况)-->
    <select id="getOneById" parameterType="int" resultMap="userMap">
        select * from user where id=#{id}
    </select>
    <resultMap id="userMap" type="cn.goktech.entity.User">
        <!--id标签指定主键,column-数据库字段名,property-类的属性名 -->
        <id column="id" property="id" />
        <result column="name" property="name"/>
        <result column="age" property="age"/>
        <result column="phone" property="phone"/>
        <result column="info" property="info"/>
    </resultMap>

    <select id="getByName" parameterType="String" resultMap="userMap">
     <!-- #{}取值时会自动拼上双引号,${}不会,${}一般主要是用于引入数据库对象 -->
        <!--    select * from user where name  like concat('%',#{name},'%') -->
         select * from user where name  like '%${name}%'
    </select>

</mapper>

如果’%${name}%’ 中指定的是name,那么在UserDao中public List getByName(@Param(“name”) String name); 的@Param的参数也是name

(4)工具类

public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;//静态唯一
    static {
        InputStream is = MybatisUtil.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    }
    //加载配置——>得到工厂——>得到会话
    //获取SqlSession的方法
    public static SqlSession openSession(){
        return  sqlSessionFactory.openSession();
    }
}

session是Mybatis与数据库之间的会话

(5)增删改查

public class Test {
    public static void main(String[] args) {
        SqlSession session = MybatisUtil.openSession();
        //Mybatis工作流程:加载配置——>解析sql——>执行并返回结果集——>结果映射
        User user = session.selectOne("cn.goktech.dao.UserDao.getById",1002);
        System.out.println(user);

        System.out.println("-----------------------");
        UserDao dao = session.getMapper(UserDao.class);
        List<User> all = dao.getAll();
        for (User u:all){
            System.out.println(u);
        }

        System.out.println("--------------------------");
        User user1 = new User();
        user1.setId(1003);
        user1.setName("David");
        user1.setInfo("优秀");
        int count = dao.updateUser(user1);
        session.commit(); //手动提交事务
        System.out.println(count);

        System.out.println("---------------");
        Map<String, Object> map = dao.getOne(1001);
        for (Map.Entry<String,Object> e:map.entrySet()){
            System.out.println(e.getKey()+"——"+e.getValue());
        }

        System.out.println("-------------------");
        User user2 = dao.getOneById(1001);
        System.out.println(user2);

        System.out.println("---------------------");
        List<User> userList= dao.getByName("i");
        for(User u:userList){
            System.out.println(u);
        }
    }
}

4.#{},${},@Param

#{}取值时会自动拼上双引号,${}不会, ${}一般主要是用于引入数据库对象
例如:

<select id="getByName" parameterType="String" resultMap="userMap">
     select * from user where name  like concat('%',#{name},'%') 
</select>
<select id="getByName" parameterType="String" resultMap="userMap">
     select * from user where name  like '%${name}%'
</select>

@Param指定参数名

public List<User> getByName(@Param("name") String name);

Mapper文件取值:

select * from user where name  like '%${name}%'

如果@Param不指定参数名
则:

select * from user where name  like '%${value}%'

5.resultMap

resultMap给定映射关系 (针对字段名与属性不同,从而不能自动封装的情况)
id标签指定主键,column-数据库字段名,property-类的属性名
示例代码:

<select id="getOneById" parameterType="int" resultMap="userMap">
        select * from user where id=#{id}
    </select>
    <resultMap id="userMap" type="cn.goktech.entity.User">
        <id column="id" property="id" />
        <result column="name" property="name"/>
        <result column="age" property="age"/>
        <result column="phone" property="phone"/>
        <result column="info" property="info"/>
    </resultMap>

Mybatis中Mapper.xmlSQL语句中大小于符号的转义写法

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值