springboot mybatis

一、首先添加maven引用,javax.xml.bind不添加会报错 java.lang.ClassNotFoundException: javax.xml.bind.DatatypeConverterjava

<!-- 持久层mybatis框架 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

<!-- 数据库驱动程序 -->
<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <scope>runtime</scope>
</dependency>

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

 

二、在resource中添加文件夹mapper,添加xml文件web

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo1.mapper.BusinessMapper">

    <resultMap type="com.example.demo1.domain.Business" id="businessResult">
        <id property="businessID" column="businessID"/>
        <result property="loanKind" column="LoanKind"></result>
        <result property="productType" column="ProductType"></result>

        <collection property="bills" ofType="com.example.demo1.domain.Bill">
            <id property="billID" column="BillID"/>
            <result property="billMonth" column="BillMonth"/>
            <result property="billType" column="BillType"/>
            <result property="billStatus" column="BillStatus"/>
        </collection>
    </resultMap>

    <select id="getBusiness" resultMap="businessResult">
      SELECT * FROM dbo.Business b
      JOIN dbo.Bill bi ON b.BusinessID=bi.BusinessID
      WHERE b.BusinessID=#{0}
   </select>

    <select id="getBusinessOne" resultType="com.example.demo1.domain.Business">
      SELECT * FROM dbo.Business WHERE BusinessID=#{0}
   </select>

</mapper>

三、添加package为domain层,而后添加实体类spring

package com.example.demo1.domain;

import lombok.Data;

import java.util.List;

@Data
public class Business {
    private int businessID;
    private String loanKind;
    private Integer productType;
    List<Bill> bills;
}
package com.example.demo1.domain;

import lombok.Data;

@Data
public class Bill {

    private int billID;
    private String billMonth;
    private int billType;
    private int billStatus;
}

四、添加package为mapper层,而后添加映射xml的方法,注意:没法进行方法的重载,必须保证方法名惟一。sql

package com.example.demo1.mapper;

import com.example.demo1.domain.Business;

public interface BusinessMapper {
    Business getBusinessOne(int id);

    Business getBusiness(int id);
}

五、添加package为service层,而后添加服务层数据库

package com.example.demo1.service;

import com.example.demo1.domain.Business;
import com.example.demo1.mapper.BusinessMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BusinessService {
    @Autowired
    private BusinessMapper businessMapper;

    public Business getBusinessOne(int id) {
        return businessMapper.getBusinessOne(id);
    }

    public Business getBusiness(int id) {
        return businessMapper.getBusiness(id);
    }
}

六、而后添加控制器层apache

package com.example.demo1.controller;

import com.example.demo1.domain.Business;
import com.example.demo1.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {
    @Autowired
    private BusinessService businessService;

    @GetMapping("/home/index/{id}")
    public Business index(@PathVariable("id") int id) {
        return businessService.getBusinessOne(id);
    }

    @GetMapping("/home/bill/{id}")
    public Business bill(@PathVariable("id") int id) {
        return businessService.getBusiness(id);
    }
}

七、而后在main函数,也就是启动类中添加扫描mapper的接口层api

package com.example.demo1;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.demo1.mapper")
public class Demo1Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class, args);
    }
}

八、application.yml文件中添加数据库链接配置和mybatis的xml配置mybatis

spring:
  datasource:
    driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
    url: jdbc:sqlserver://192.168.1.1:1433;database=PostLoan;
    username: sa
    password: 123456
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.demo1.domain

项目结构图app

 

注意事项:框架

一、resource文件夹中的mapper文件夹中的xml文件的命名空间,就是代码的mapper层,须要具体到mapper层中的接口,好比在本示例中的xml的命名空间就是下面这样

<mapper namespace="com.example.demo1.mapper.BusinessMapper">

在代码的mapper层中有个BusinessMapper的接口,具体到接口名。

二、代码mapper的接口方法必定要和xml中的id相对应。

三、配置文件中mybatis配置type-aliases-package配置项是指向代码中的POJO层,通常都使用彻底限定名了。

四、若是不想在接口层,也就是mapper层的每一个类上添加@Mapper注解,那么必定要在启动类上添加@MapperScan注解,来扫描mapper层的全部接口。

 

以上是基于xml的写法,还能够基于注解方式来写sql

package com.example.demo1.mapper;

import com.example.demo1.domain.Instruction;
import org.apache.ibatis.annotations.Select;

public interface IInstruction {
    @Select("SELECT * FROM pay.DeductInstruction where DeductInstructionID=#{id}")
    Instruction getInstruction(int id);
}

传参方式:

方式一 貌似只再xml生效,慎用,不想验证了。我记得用过。

@Select("SELECT * FROM XXX WHERE created_time>=#{arg0} AND created_time<#{arg1}")
public List<XXX> getXXXInfo(String startTime, String endTime);

方式二 经常使用方式

@Select("SELECT * FROM t_dz_channel_info WHERE created_time>=#{startTime} AND created_time<#{endTime}")
public List<DzChannelInfoPO> getDzChannelInfo(@Param("startTime") String startTime, @Param("endTime") String endTime);

批量插入

//批量插入
@Insert({
        "<script>",
        "INSERT INTO table",
        "(filed1,filed2,filed3,created_time,updated_time)",
        "VALUES",
        "<foreach collection='data' item='item' index='index' separator=','>",
        "(#{item.filed1},#{item.filed2},#{item.filed3},{item.createdTime},#{item.updatedTime})",
        "</foreach>",
        "</script>"
})
int insertList(@Param(value = "data") List<xxxPO> data);
@Insert("INSERT INTO student(name, age) VALUES(#{name}, #{age})")
int insertByUser(Student student);
@Update("UPDATE student SET age=#{age} WHERE name=#{name}")
void update(Student student);

 

mybatis动态sql实现方案:将select注解换成下面注解,同时定义一个类xxx,类中方法aaa,返回一个string类型便可,在aaa方法中组装sql.

@SelectProvider(type = xxx.class,method = "aaa")

 

mybatis 实现打印sql的方法一:配置文件添加,其中com.example.demo.mapper是mapper接口所在包

logging:
  level:
    com.example.demo.mapper: debug

方法二:我用了mybatis-plus这个配置就会无效,须要将mybatis换成mybatis-plus便可

mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
相关文章
相关标签/搜索