zoukankan      html  css  js  c++  java
  • Mybatis配置和基于配置的使用

    导入jre包后还需要配置xml文件

    配置文件mybatis-config.xml
    在src目录下创建mybatis的主配置文件mybatis-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>
        //自动扫描com.blog.bean下的类型,使得在后续配置文件UserMapper.xml中使用resultType的时候,可以直接使用类名(User),而不必写全com.blog.bena.User
        <typeAliases>
          <package name="com.blog.bean"/>
        </typeAliases>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
            //value:提供连接数据库用的驱动
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
            //value:数据库名称
                    <property name="url" value="jdbc:mysql://localhost:3306/blog"/>
                    //value:数据库账号
            <property name="username" value="root"/>
            //value:数据库密码
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        //映射UserMapper.xml
        <mappers>
            <mapper resource="com/how2java/pojo/Category.xml"/>
        </mappers>
    </configuration>

    在包com.blog.mapper下,新建文件UserMapper.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">
        //表示命名空间是com.blog.mapper
        <mapper namespace="com.blog.mapper">
        //id: selectUserById 进行标示以供后续代码调用,resultType="User" 表示返回的数据和User关联起来,这里本应该使用的是 com.blog.bean.User, 但是因为上一步配置了别名,所以直接使用User就行了
            <select id="selectUserById" resultType="User">
                select * from user where uid = #{uid};  
            </select>
        </mapper>

    在java中调用:

    //mybatis-config.xml文件路径:com.blog.config.mybatis-config.xml
    String resource= "com/blog/config/mybatis-config.xml";
    InputStream is = null;
    try {
        is = Resources.getResourceAsStream(resource);
    } catch (IOException e) {
        e.printStackTrace();
    }
    SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);
    SqlSession sqlSession = ssf.getFactory().openSession();
    //"com.blog.mapper.UserMapper.selectUserById"也可以写成"selectUserById",前提是多个配置文件下没有相同id
    User u = (User)sqlSession .selectOne("selectUserById", 1);


    添加:insert into
    //parameterType参数类型为User类型
    <insert id="addUser" parameterType="User">
            insert into user(uname,usex,upass) values (#{uname},#{usex},#{upass});
    </insert>
    调用方式:
    User u = new User("张三","男",123456);
    sqlSession .insert("com.blog.mapper.UserMapper.addUser", user);
    //在对数据库执行增加、修改、删除操作时,需要进行commit和close,否则无法生效并耗费资源
    sqlSession.commit();
    sqlSession.close();

    删除:delete
    <delete id="deleteUser">
            delete from user where uid = #{uid};
    s</delete>

    查询:select
    <select id="selectUserById" resultType="User">
            select * from user where uid = #{uid};  
    </select>

    修改:update
    <update id="updateUser" parameterType="User" >
        update User set uname=#{uname} where uid=#{uid}    
    </update>

    查询对象的集合:
    <select id="selectAllUser" resultType="User">
        select * from user;
    </select>
    调用SqlSession对象的selectList("selectAllUser")方法

    模糊查询:
    <select id="listUserByUnameId" resultType="User">
         select * from user where  uname like concat('%',#{uname},'%')
    </select>

    多条件查询:例如分页,可以使用parameterType="map",参数类型为map集合
    <select id="listUserPage" parameterType="map" resultType="User">
          select * from user limit #{begin},#{size}
    </select>
    调用方法:
    Map<String ,Object> map = new HashMap<>();
        map.put("begin", 0);
        map.put("size", 3);
    List<User> list = sqlSession.selectList("listUserPage", map);

    一对多查询:collection、ofType
    一个用户可以发多个博客,User类有个List<Blog> list属性
    <resultMap type="User" id="Userpojo">
            //子元素id代表resultMap的主键,而result代表其属性。
            //id是作为唯一标识的,用在和其他对象实例对比时
        <id column="uid" property="uid"/>
        <result column="unick" property="unick"/>
            //property: 指的是User类中Blog集合的变量名, ofType:指的是集合中元素的类型
        <collection property="list" ofType="Blog">
                <id column="bid" property="bid"/>
                <result column="btitle" property="btitle"/>
        </collection>
    </resultMap>
    <select id="selectUserAndBlogs" resultMap="Userpojo">
           select unick,btitle from user inner join blog on buid=uid where uid=#{uid}
    </select>

    多对一查询:association、javaType
    多个博客属于一个用户,Blog类有个User user属性
    <resultMap type="Blog" id="Blogpojo">
        <id column="bid" property="bid"/>
            <result column="btitle" property="btitle"/>
            //property: 指的是属性名称, javaType:指的是属性的类型
            <association property="user" javaType="User">
                <id column="uid" property="uid"/>
                <result column="unick" property="unick"/>
            </association>
    </resultMap>
    <select id="selectBlogAndUser" resultMap="Blogpojo">
            select unick,btitle from blog inner join user on buid=uid 
    </select>


    多对多查询:
    一个用户可以发多个博客,User类有个List<Blog> listBlog属性,Blog有评论集合List<Comment> clist
    <resultMap type="User" id="userblogscomments">
            <id column="uid" property="uid"/>
            <result column="unick" property="unick"/>
            <collection property="list" ofType="Blog">
                <id column="bid" property="bid"/>
                <result column="btitle" property="btitle"/>
    //在最内层的collection、association可以通过上层的结果集column,调用查询语句select直接查询
                <collection property="clist" column="bid" select="selectCommentss">
                </collection>
            </collection>
    </resultMap>
    <select id="selectUserss" resultMap="userblogscomments" parameterType="int">
            select * from user inner join blog on buid=uid  where uid=#{uid}
    </select>
    <select id="selectCommentss" parameterType="int" resultType="Comment">
            select * from comment where cbid=#{bid}
    </select>

  • 相关阅读:
    Constants and Variables
    随想
    C#基础篇之语言和框架介绍
    Python基础19 实例方法 类方法 静态方法 私有变量 私有方法 属性
    Python基础18 实例变量 类变量 构造方法
    Python基础17 嵌套函数 函数类型和Lambda表达式 三大基础函数 filter() map() reduce()
    Python基础16 函数返回值 作用区域 生成器
    Python基础11 List插入,删除,替换和其他常用方法 insert() remove() pop() reverse() copy() clear() index() count()
    Python基础15 函数的定义 使用关键字参数调用 参数默认值 可变参数
    Python基础14 字典的创建修改访问和遍历 popitem() keys() values() items()
  • 原文地址:https://www.cnblogs.com/snzd9958/p/10099011.html
Copyright © 2011-2022 走看看