springboot下使用mybatis的方法

时间:2022-11-13 19:40:51

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

详见

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

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

?
1
2
3
4
5
<dependency> 
  <groupId>org.mybatis.spring.boot</groupId> 
  <artifactId>mybatis-spring-boot-starter</artifactId> 
  <version>1.1.1</version> 
</dependency>

application.properties 添加相关配置

?
1
2
3
4
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中,对了你一切都不用管了,直接拿起来使用就行了。

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

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

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

?
1
2
3
4
5
6
7
@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模式开发

注解模式

?
1
2
3
4
5
@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需要新增

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

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

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

指定mybatis基础配置文件

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

?
1
2
3
4
5
6
7
8
9
10
<configuration>
  <typeAliases>
    <typeAlias alias="Integer" type="java.lang.Integer" />
    <typeAlias alias="Long" type="java.lang.Long" />
    <typeAlias alias="HashMap" type="java.util.HashMap" />
    <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
    <typeAlias alias="ArrayList" type="java.util.ArrayList" />
    <typeAlias alias="LinkedList" type="java.util.LinkedList" />
  </typeAliases>
</configuration>

编写Dao层的代码

?
1
2
3
public interface CityDao {
  public City selectCityByState(String State);
}

对应的xml映射文件

?
1
2
3
4
5
6
7
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.demo.dao.CityDao">
  <select id="selectCityByState" parameterType="String" resultType="City">
    select * from city where state = #{state}
  </select></mapper>

总结

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

原文链接:http://www.jianshu.com/p/13616babe6ae