Mybatis

Mybatis

1.搭建环境

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

  1. 创建一个mavan项目

  2. 导入依赖

    1. 
           
            mysql
               mysql-connector-java
            5.1.47
           
           
               org.mybatis
               mybatis
               3.5.2
           
           
               junit
               junit
               4.12
           
       
      
      
  3. 修改配置,能够自动导入所有xml和properties 文件

        
            
                
                    src/main/resources
                    
                        **/*.xml
                        **/*.properties
                    
                
                
                    src/main/java
                    
                        **/*.xml
                        **/*.properties
                    
                
            
        
    
  4. 在resources 配置mysql数据库

    
    
    
      
        
          
          
            
            
            
            
          
        
      
      
        
      
    
    
    • ${driver} : 使用的驱动 一般使用com.mysql.jdbc.Driver
    • ${url}:数据库地址
    • ${username}:用户名
    • ${password}:密码
    
    
    
        
            
                
                
                    
                    
                    
                    
                
            
        
        
    
        
    
    
  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插件

              
                  org.projectlombok
                  lombok
                  1.18.10
              
      
    • 代码:

      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 getTags();
            void addTag(Tag tag);
            void deleteTag(int id);
            void updateTag(Tag tag);
        }
        
        
        
        
        
        
            
            
                insert into tag values (#{id}, #{name});
            
            
                delete from tag where id=#{id};
            
            
                update tag set name=#{name} where id=#{id};
            
        
        

        xml 文件:

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

         
      
          
          
      
      
      
      
      
      
          
          
              insert into tag values (#{id}, #{name});
          
          
              delete from tag where id=#{id};
          
          
              update tag set name=#{name} where id=#{id};
          
      
      
      • 一对多和多对一:

        
        
        
        
            
                
                
            
        
            
            
                insert into post(content, author, cid, tid) values ( #{content},#{author},#{category.id},#{tag.id});
            
            
                delete from post where id=#{id};
            
            
                update post set content=#{content}, author=#{author}, cid=#{category.id}, tid=#{tag.id};
            
            
            
        
        
        package com.test.mapper;
        
        import com.test.pojo.Post;
        
        import java.util.List;
        
        public interface PostMapper {
            List getPosts();
            void addPost(Post post);
            void deletePost(int id);
            void updatePost(Post post);
        }
        
        

其他内容

动态sql+map 做多条件查询

    

你可能感兴趣的:(Mybatis)