[Mybaits]1.如何建立Mybatis项目


1.导入各种依赖

点击查看代码
        
            mysql
            mysql-connector-java
            8.0.22
        
        
            junit
            junit
            4.12
            test
        
        
        
            org.mybatis
            mybatis
            3.5.2
        
### 2.在resources中建立mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>


    
        
            
            
                
                
                
                
            
        
    

3.写Mybatis工具类:获得SQLSession

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        //获得SqlSessionFactory
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //获得SqlSession
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

4.新建实体类、新建Dao接口

5.建立Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>


    

注意namespace为Dao接口的地址,id必须和接口中的对应方法名一致!

此外,还需要去pom.xml配置


    
        
            src/main/resources
            
                **/*.properties
                **/*.xml
            
             true
        
        
            src/main/java
            
                **/*.properties
                **/*.xml
            
            true
        
    

6.去mybatis-config.xml中注册mapper


  

注意不能用 . 必须用 /