mybasic

作者: 章晓赟 | 来源:发表于2017-06-09 19:10 被阅读0次

    mybatis概念

    概念:一个持久层框架

    作用:ORM将sql语句映射成实体类

    特点:

    巧灵活

    半自动化
    使用与中小型项目的开发

    mybatis入门

    1.png

    1、创建mybatis-config.xml文件

    <!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <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:3306/bank?useUnicode=true&characterEncoding=utf-8"/>
    <property name="username" value="root"/>
    <property name="password" value=""/>
    </dataSource>
    </environment>
    </environments>
    <mappers>
    <mapper resource="UserMapper.xml"/>
    </mappers>
    </configuration>

    2、创建映射文件UserMapper.xml

    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

    <mapper namespace="user">
    <select id="selectUser" resultType="com.hemi.mybatis.bean.User">
    select * from user where uid=1;
    </select>
    </mapper>

    3、获取xml配置文件

    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");

    4、创建SqlSessionFactory

    SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);

    5、获取SqlSession

    SqlSession sqlSession = factory.openSession();

    6、调用SqlSession的selectOne(命名空间.id名称);

    Object object = sqlSession.selectOne("user.selectUser");

    7、关闭SqlSession

    sqlSession.close();

    增删改

    Some_Text

    <insert id="insertUser" parameterType="com.hemi.mybatis.bean.User">

    insert into user (username,password) values(#{username},#{password});
    </insert>

    <update id="updateUser" parameterType="com.hemi.mybatis.bean.User">
    update user set username=#{username},password=#{password} where uid=#{uid}
    </update>

    Some_Text

    <delete id="deleteUser" parameterType="int">
    delete from user where uid=#{value}
    </delete>

    Mapper接口开发

    一、定义一个接口

    public interface TypeMapper {
    Type selectType(int typeid);
    }

    二、定义一个mapper.xml映射文件

    mapper文件的要求:

    namespace的值就是对象接口的全类名,并且类名和xml文件名保持一致
    id的值就是抽象方法
    resultType的值必须和抽象方法的返回值一致
    parameterType的值和抽象方法的参数类型一致
    注意 mapper.xml文件的约束是mapper.dtd,不是config.dtd

    三、使用

    将mybatis入门步骤中的步骤六改为如下代码:

    TypeMapper mapper=sqlSession.getMapper(TypeMapper.class);
    Type type=mapper.selectType(1);

    相关文章

      网友评论

          本文标题:mybasic

          本文链接:https://www.haomeiwen.com/subject/hbmfqxtx.html