springboot mybatis

南楼画角 提交于 2021-01-17 17:06:11

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

<!-- 持久层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>

 

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

<?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>

3、添加package为domain层,然后添加实体类

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;
}

4、添加package为mapper层,然后添加映射xml的方法,注意:无法进行方法的重载,必须保证方法名唯一。

package com.example.demo1.mapper;

import com.example.demo1.domain.Business;

public interface BusinessMapper {
    Business getBusinessOne(int id);

    Business getBusiness(int id);
}

5、添加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);
    }
}

6、然后添加控制器层

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);
    }
}

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

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);
    }
}

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

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

项目结构图

 

注意事项:

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

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

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

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

3、配置文件中mybatis配置type-aliases-package配置项是指向代码中的POJO层,可以扫描自定义类型,一般都使用完全限定名了。

4、如果不想在接口层,也就是mapper层的每个类上添加@Mapper注解,那么一定要在启动类上添加@MapperScan注解,来扫描mapper层的所有接口。

5、mapper-locations:这个玩意,我在使用springboot+mybatis plus时候发现不指定其实也是可以的,在resource目录下创建mapper文件夹,就会自动扫描此文件夹下所有xml文件(今天在另外一个项目中不加就不行。。。。原因是plus版本在3.2.0以后才会自动读取。。。)。

这里还要注意plus 3.2.0 mapper-locations: 会有默认值,但是再mssql中不支持LocalDateTime类型。所以还是降回3.1.0吧。。。

以上是基于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);

注意:如果报错说参数无法验证什么的,需要在方法参数加个注解Param(value = "data"),其中data就是sql中使用的参数。

 

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

 

突然看到纯洁写的,写的很不错,附个链接:https://www.cnblogs.com/ityouknow/p/6037431.html

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!