SpringBoot整合Mybatis

Posted 旺仔的小窝

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot整合Mybatis相关的知识,希望对你有一定的参考价值。

 

springBoot整合Mybatis

1.导入依赖

    <dependencies>
        <!-- web支持,SpringMVC, Servlet支持等 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>

        <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>

        <!-- jstl for jsp page -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.7</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--activceMq-->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-core</artifactId>
            <version>5.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>


    </dependencies>

    <properties>
        <java.version>1.8</java.version>
        <!-- 修改thymeleaf的版本 -->
        <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
    </properties>
    <!--<build>-->
        <!--<resources>-->
            <!--<resource>-->
                <!--<directory>src/main/java</directory>-->
                <!--<includes>-->
                    <!--<include>**/*.xml</include>-->
                    <!--<include>**/*.properties</include>-->
                <!--</includes>-->
                <!--<filtering>true</filtering>-->
            <!--</resource>-->
            <!--<resource>-->
                <!--<directory>src/main/resources</directory>-->
                <!--<includes>-->
                    <!--<include>**/*.xml</include>-->
                    <!--<include>**/*.properties</include>-->
                <!--</includes>-->
                <!--<filtering>true</filtering>-->
            <!--</resource>-->
        <!--</resources>-->
    <!--</build>-->

2.建立dao层

1.编写mybatis总配置文件(mybatis-config.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <settings>
        <setting name="cacheEnabled"             value="true" />  <!-- 全局映射器启用缓存 -->
        <setting name="useGeneratedKeys"         value="true" />  <!-- 允许 JDBC 支持自动生成主键 -->
        <setting name="defaultExecutorType"      value="REUSE" /> <!-- 配置默认的执行器 -->
        <setting name="logImpl"                  value="SLF4J" /> <!-- 指定 MyBatis 所用日志的具体实现 -->
        <!-- <setting name="mapUnderscoreToCamelCase" value="true"/>  驼峰式命名 -->
    </settings>
    
</configuration>

3.编写实体类和Mapper接口和mapper配置文件

1.实体类实现 Serializable接口

2.mapper接口和mapper配置文件满足mybatis框架的要求

3.编写application总配置文件

spring:
  thymeleaf:
    cache: false
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/security?characterEncoding=utf-8&useSSL=false
    username: root
    password: 
mybatis:
  # 搜索指定包别名
  typeAliasesPackage: 
  # 配置mapper的扫描,找到所有的mapper.xml映射文件
  mapperLocations: classpath*:mybatis/mapper/*.xml
  # 加载全局的配置文件
  configLocation: classpath:mybatis/mybatis-config.xml

4.springBoot的注解

1.@SpringBootApplication

包括:@Configuration,@EnableAutoConfiguration,@ComponentScan

(1)@Configuration:提到@Configuration就要提到他的搭档@Bean。使用这两个注解就可以创建一个简单的spring配置类,可以用来替代相应的xml配置文件。

@Configuration 
public class Conf { 
    @Bean 
    public Car car() { 
        Car car = new Car(); 
        car.setWheel(wheel()); 
        return car; 
    } 
    @Bean  
    public Wheel wheel() { 
        return new Wheel(); 
    } 
}

(2)@EnableAutoConfiguration:能够自动配置spring的上下文,试图猜测和配置你想要的bean类,通常会自动根据你的类路径和你的bean定义自动配置。

(3)@ComponentScan:会自动扫描指定包下的全部标有@Component的类,并注册成bean,当然包括@Component下的子注解@Service,@Repository,@Controller。

@RestController

注解那么返回的结果会自动解析为json格式的字段,如果加@Controller注解,那么图中"return json;"便会解析为json.html,并去寻找该页面,而不是返回json中的内容。

@EnableTransactionManagement为加事务管理。

@Mapper注解

作用:在接口类上添加了@Mapper,在编译之后会生成相应的接口实现类添加位置:接口类上面

@MapperScan()

作用:指定要变成实现类的接口所在的包,然后包下面的所有接口在编译之后都会生成相应的实现类添加位置:是在Springboot启动类上面添加。

@Select({"select id,user_name,user_password,user_email,user_info,head_img,create_time from sys_user where id = #{id}"})
    @Results(id="userMap", value={
            @Result(column="id", property="id", id=true),
            @Result(column="user_name", property="userName"),
            @Result(column="user_password ", property="userPassword"),
            @Result(column="user_email", property="userEmail"),
            @Result(column="user_info", property="userInfo"),
            @Result(column="head_img", property="headImg", jdbcType=JdbcType.BLOB),
            @Result(column="create_time", property="createTime", jdbcType=JdbcType.TIMESTAMP)
    })
    SysUser selectUserByUserId(Long id);
    
    @Select({"select * from sys_user"})
    @ResultMap("userMap")
    List<SysUser> selectUsers();


@Results注解表示属性信息为一个resultMap,id则是命名空间内识别该resultMap的唯一标识,
column和property及其其他属性与在resultMap标签内定义方式相同。 此处的定义,@Results注解必须与@Select查询同方法在一起,不可以单独定义@Results注解,
会不被识别的。定义后,在其他方法处,便可以使用该@Results定义的resultMap了。

一对一注解 @One()

public interface PersonMapper {

    @Select("select * from tb_person where id= #{id}")
    @Results({
            @Result(id=true,column = "id",property = "id"),
            @Result(column = "name",property = "name"),
            @Result(column = "age",property = "age"),
            @Result(column = "sex",property = "sex"),
            @Result(column = "card_id",property = "card",one = @One(select = "org.arunner.mapper.CardMapper.selectCardById",fetchType = FetchType.EAGER)),
    })
    Person selectPersonById(Integer id);

}

fetchType :延迟加载类型
@One():一对一注解

一对多注解many = @Many()

public interface ClazzMapper {

    @Select("select * from tb_clazz where id= #{id}")
    @Results({
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "name",property = "name"),
            @Result(column = "code",property = "code"),
             //@many注解的select属性表示需要关联执行的SQL语句
             //FetchType.LAZY表示查询的类型是延迟加载
            @Result(column = "id",property = "students",many = @Many(select = "org.fkit.mapper.StudentMapper.selectByClazzId",fetchType = FetchType.LAZY)),
    })
    //根据ID查询班级信息
    Clazz selectById(Integer id);
}

多对多查询many=@many()

 

public interface IUserDao {

    //根据id得到用户:
    @Select("select * from users where uid = #{uid}")
    @Results({
            @Result(id=true,column="uid",property="uid"),
            @Result(column="uname",property="uname"),
            @Result(column="uid",property="roles",
                    many=@Many(
                            select="com.desert.dao.IRolesDao.getAllRolesByuid",
                            fetchType= FetchType.LAZY
                    )
            )
    })
    public Users getUsersById(int uid);

}

public interface IRolesDao {

    //根据用户id得到所有的角色:

    @Select("select * from roles where rid in(select rid from u_r where uid=1)")
    public List<Roles> getAllRolesByuid(int uid);


}

以上是关于SpringBoot整合Mybatis的主要内容,如果未能解决你的问题,请参考以下文章

springboot整合mybatis,redis,代码

SpringBoot系列Mybatis整合

SpringBoot系列Mybatis整合

springboot整合mybatis开发

18.springboot整合mybatis

SpringBoot:4.SpringBoot整合Mybatis实现数据库访问