网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

springboot下使用mybatis的方法

使用mybatis-spring-boot-starter即可。 简单来说就是mybatis看见spring boot这么火,于是搞出来mybatis-spring-boot-starter这个解决方案来与springboot更好的集成

创新互联建站主要从事网站设计、成都网站制作、网页设计、企业做网站、公司建网站等业务。立足成都服务阿勒泰,10年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:028-86922220

详见

http://www.mybatis.org/spring/zh/index.html

引入mybatis-spring-boot-starter的pom文件

  
  org.mybatis.spring.boot  
  mybatis-spring-boot-starter  
  1.1.1  

application.properties 添加相关配置

spring.datasource.driverClassName = com.MySQL.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/city?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = mysql

springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对了你一切都不用管了,直接拿起来使用就行了。

mybatis.type-aliases-package=com.test.demo.model

这个配置用来指定bean在哪个包里,避免存在同名class时找不到bean

在启动类中添加@MapperScan指定dao或者mapper包的位置,可以用 {"",""}的形式指定多个包

@SpringBootApplication
@MapperScan("com.test.demo.dao")
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

或者直接在Mapper类上面添加注解@Mapper也可以指定mapper,建议使用上面这种,给每个mapper加个注解挺麻烦不说,如果是dao的包,还是要用@MapperScan来指定位置

接下来,可以用注解模式开发mapper,或者用xml模式开发

注解模式

@Mapper
public interface CityMapper {
  @Select("select * from city where state = #{state}")
  City findByState(@Param("state") String state);
}

@Select 是查询类的注解,所有的查询均使用这个 @Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。 @Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值 @Update 负责修改,也可以直接传入对象 @delete 负责删除 了解更多注解参考这里

http://www.mybatis.org/mybatis-3/zh/java-api.html

xml模式

xml模式保持映射文件的老传统,application.properties需要新增

mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

指定mybatis的映射xml文件位置 此外,还可以指定mybatis的配置文件,如果需要增加mybatis的一些基础配置,可以增加下面的配置

mybatis.config-locations=classpath:mybatis/mybatis-config.xml

指定mybatis基础配置文件

mybatis-config.xml可以添加一些mybatis基础的配置,例如


  
    
    
    
    
    
    
  

编写Dao层的代码

public interface CityDao {
  public City selectCityByState(String State);
}

对应的xml映射文件



  

总结

以上所述是小编给大家介绍的springboot下使用mybatis的方法,希望对大家有所帮助!


新闻标题:springboot下使用mybatis的方法
浏览路径:http://bjjierui.cn/article/ppdjpp.html

其他资讯