SpringMVC SSM框架笔记二:xml配置Mybatis

spring整合mybatis有多重方式

  • xml配置Mybatis,代码通过mybatis的xml配置生成SqlSessionFactory(这种方法已过时)

原始xml方式整合

通过maven引入SpringMVC和Mybatis包


    org.springframework
    spring-webmvc
    5.1.10.RELEASE




    org.mariadb.jdbc
    mariadb-java-client
    2.4.4



    org.mybatis
    mybatis
    3.5.2

创建表结构

CREATE TABLE tb_province (
    id int PRIMARY KEY AUTO_INCREMENT COMMENT '自增主键',
    province varchar(255) NULL COMMENT '省份中文名'
);

创建数据库表映射class

class TbProvinceEntity {
    var id: Int? = null
    var province: String? = null
}

创建Dao层接口

/**
 * 注解:@Mapper 必须添加,否则不会生成对应的实现子类
 */
@Mapper
interface ProvinceMapper {
    fun getList(): List
}

建立 db.properties 配置数据库(一般存放在resource目录)

#db.properties 文件内容

jdbc.driver=org.mariadb.jdbc.Driver
jdbc.url=jdbc:mariadb:/xx.com:8700/test
jdbc.username=xxx
jdbc.password=xxx

resource文件夹下建立MyBatis配置文件

mybatis-config.xml 文件




     
    
         
         
    
     
        
             
             
                
                
                
                
            
        
    
    
        
        

        
        

        
        

        
        
    


使用方法

/**
 * 配置文件需要打包放在运行时项目的根目录下
 * mybatis-config.xml
 * 使用builder设计模式创建SessionFactory:SqlSessionFactoryBuilder
 * 使用ClassPathResource加载配置资源
 */
val sessionFactory = SqlSessionFactoryBuilder().build(ClassPathResource("mybatis-config.xml").inputStream)
val session = sessionFactory.openSession()
val provinceMapper = session.getMapper(ProvinceMapper::class.java)
provinceMapper.getList()

你可能感兴趣的:(SpringMVC SSM框架笔记二:xml配置Mybatis)