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
相關文章
相關標籤/搜索