springboot下使用mybatis的方法

网友投稿 273 2023-03-14


springboot下使用mybatis的方法

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

详见

http://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://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映射文件

PUBLIC "sfcqMV-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

select * from city where state = #{state}

总结

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:api接口文档设计工具(api接口文档设计工具在哪)
下一篇:列表设计接口测试用例(完整的接口测试用例excel)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~