Mybatis

作者: Hao_38b9 | 来源:发表于2020-05-29 21:33 被阅读0次

Mybatis

1.搭建环境

https://mybatis.org/mybatis-3/zh/index.html

  1. 创建一个mavan项目

  2. 导入依赖

    1. <dependencies>
           <dependency>
            <groupId>mysql</groupId>
               <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
           </dependency>
           <dependency>
               <groupId>org.mybatis</groupId>
               <artifactId>mybatis</artifactId>
               <version>3.5.2</version>
           </dependency>
           <dependency>
               <groupId>junit</groupId>
               <artifactId>junit</artifactId>
               <version>4.12</version>
           </dependency>
       </dependencies>
      
      
  3. 修改配置,能够自动导入所有xml和properties 文件

        <build>
            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.properties</include>
                    </includes>
                </resource>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.properties</include>
                    </includes>
                </resource>
            </resources>
        </build>
    
  4. 在resources 配置mysql数据库

    <?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="development">
        <environment id="development">
          <transactionManager type="JDBC"/>
          <dataSource type="POOLED">
            <property name="driver" value="${driver}"/>
            <property name="url" value="${url}"/>
            <property name="username" value="${username}"/>
            <property name="password" value="${password}"/>
          </dataSource>
        </environment>
      </environments>
      <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
      </mappers>
    </configuration>
    
    • ${driver} : 使用的驱动 一般使用com.mysql.jdbc.Driver
    • ${url}:数据库地址
    • ${username}:用户名
    • ${password}:密码
    <?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="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/blogData?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
    
        </mappers>
    </configuration>
    
  5. 创建一个数据库

    CREATE DATABASE blogData;
    
  6. 创建数据表

    use blogData;
    CREATE TABLE IF NOT EXISTS `Category`(
        `id` INT UNSIGNED AUTO_INCREMENT,
        `name` VARCHAR(100) NOT NULL,
        PRIMARY KEY(`id`)
    ) ENGINE =InnoDB DEFAULT CHARSET =utf8;
    CREATE TABLE IF NOT EXISTS `Tag`(
        `id` INT UNSIGNED AUTO_INCREMENT,
        `name` VARCHAR(100) NOT NULL ,
        PRIMARY KEY (`id`)
    )ENGINE = InnoDB DEFAULT CHARSET = utf8;
    CREATE TABLE IF NOT EXISTS `Post`(
         `id` INT UNSIGNED AUTO_INCREMENT,
         `content` VARCHAR(1000) NOT NULL,
         `author` VARCHAR(100) NOT NULL,
         `cid` INT UNSIGNED,
         `tid` INT UNSIGNED,
         PRIMARY KEY (id),
         FOREIGN KEY (cid) REFERENCES Category(id),
         FOREIGN KEY (tid) REFERENCES Tag(id)
    ) ENGINE=InnoDB DEFAULT CHARSET = utf8;
    
  7. 创建实体类

    • 在src下创建一个pojo目录
image-20200529003522307.png
  • 编写实体类

    • 这里可以使用lombok插件

              <dependency>
                  <groupId>org.projectlombok</groupId>
                  <artifactId>lombok</artifactId>
                  <version>1.18.10</version>
              </dependency>
      
    • 代码:

      package com.test.pojo;
      
      import lombok.Data;
      
      @Data
      public class Category {
          int id;
          String name;
      }
      
      package com.test.pojo;
      
      import lombok.Data;
      
      @Data
      public class Tag {
          int id;
          String name;
      }
      
      
      package com.test.pojo;
      
      import lombok.Data;
      
      import java.util.List;
      @Data
      public class Post {
          int id;
          String author;
          String content;
          Category category;
          Tag tag;
      }
      
      
   注意 : 类名和属性名要和数据表匹配
  1. 创建工具类

    • 创建一个utils包
image-20200529135921661.png
  • 创建MyBatisUtils 获取sqlsession

    package com.test.utils;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    public class MyBatisUtils {
        private static SqlSessionFactory sqlSessionFactory;
        static {
            try{
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession(true);
        }
    }
    
    
  • openSession(true) :可以设置自动提交

  1. 创建一个mapper包

    [图片上传失败...(image-1b690d-1590759226404)]

    • 编写实体类的映射类

      • 使用注解开发
      package com.test.mapper;
      
      import com.test.pojo.Category;
      import org.apache.ibatis.annotations.Delete;
      import org.apache.ibatis.annotations.Insert;
      import org.apache.ibatis.annotations.Select;
      import org.apache.ibatis.annotations.Update;
      
      public interface CategoryMapper {
          @Select("select * from Category")
          Category getCategorys();
          @Insert("insert into Category values(#{id},#{name})")
          void addCategory(Category category);
          @Delete("delete from Category where id=#{id}")
          void deleteCatogory(int id);
          @Update("update Category set name=#{name} where id=#{id}")
          void updateCategory(Category category);
      }
      
      
      • 使用xml 映射

        package com.test.mapper;
        
        import com.test.pojo.Tag;
        
        import java.util.List;
        
        public interface TagMapper {
            List<Tag> getTags();
            void addTag(Tag tag);
            void deleteTag(int id);
            void updateTag(Tag tag);
        }
        
        
        <?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">
        
        <mapper namespace="com.test.mapper.TagMapper">
            <select id="getTags" resultType="com.test.pojo.Tag">
                select * from tag;
            </select>
            <insert id="addTag" parameterType="com.test.pojo.Tag">
                insert into tag values (#{id}, #{name});
            </insert>
            <delete id="deleteTag">
                delete from tag where id=#{id};
            </delete>
            <update id="updateTag" parameterType="com.test.pojo.Tag">
                update tag set name=#{name} where id=#{id};
            </update>
        </mapper>
        

        xml 文件:

        • namespace: 命名空间,就是映射类的包名+类名
      • 类型别名:使用类型别名可以简化 类的导入

       <!--mybatis-config.xml -->  
      <typeAliases>
          <typeAlias type="com.test.pojo.Category" alias="Category" />
          <typeAlias type="com.test.pojo.Tag" alias="Tag" />
      </typeAliases>
      
      <?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">
      
      <mapper namespace="com.test.mapper.TagMapper">
          <select id="getTags" resultType="Tag">
              select * from tag;
          </select>
          <insert id="addTag" parameterType="com.test.pojo.Tag">
              insert into tag values (#{id}, #{name});
          </insert>
          <delete id="deleteTag">
              delete from tag where id=#{id};
          </delete>
          <update id="updateTag" parameterType="com.test.pojo.Tag">
              update tag set name=#{name} where id=#{id};
          </update>
      </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">
        
        <mapper namespace="com.test.mapper.PostMapper">
            <resultMap id="getPosts" type="com.test.pojo.Post">
                <association property="category" column="cid" select="getCategory" />
                <association property="tag" column="tid" select="getTag" />
            </resultMap>
        
            <select id="getPosts" resultMap="getPosts">
                select * from post;
            </select>
            <insert id="addPost" parameterType="com.test.pojo.Tag" useGeneratedKeys="true">
                insert into post(content, author, cid, tid) values ( #{content},#{author},#{category.id},#{tag.id});
            </insert>
            <delete id="deletePost">
                delete from post where id=#{id};
            </delete>
            <update id="updatePost" parameterType="com.test.pojo.Post">
                update post set content=#{content}, author=#{author}, cid=#{category.id}, tid=#{tag.id};
            </update>
            <select id="getCategory" resultType="com.test.pojo.Category">
                select * from category where id=#{cid};
            </select>
            <select id="getTag" resultType="com.test.pojo.Tag">
                select * from tag where id=#{tid};
            </select>
        </mapper>
        
        package com.test.mapper;
        
        import com.test.pojo.Post;
        
        import java.util.List;
        
        public interface PostMapper {
            List<Post> getPosts();
            void addPost(Post post);
            void deletePost(int id);
            void updatePost(Post post);
        }
        
        

其他内容

动态sql+map 做多条件查询

    <select id="getPost" resultMap="getPosts">
        select * from post where 1=1
        <if test="author!=null" >
            and author=#{author}
        </if>
        <if test="content!=null">
            and content like '%#{content}%'
        </if>
    </select>

相关文章

网友评论

      本文标题:Mybatis

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