Spring Boot系列7-SpringBoot+mybatis+druid+TypeHandler

點擊閱讀原文
介紹在SpringBoot中集成mybatis和druid以及自定義TypeHandler

創建數據庫表

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- 創建student表
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
  `parent_phone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '家長電話號碼逗號分隔',
  `city` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '居住城市json格式存儲{\"province\":\"廣東省\",\"city\":\"深圳市\",\"district\":\"南山區\"}',
  `net_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '網名逗號分隔',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- 插入學生信息
-- ----------------------------
INSERT INTO `student` VALUES (1, '小英', '13222222222,13333333333,15777777777', '{\"province\":\"廣東省\",\"city\":\"深圳市\",\"district\":\"南山區\"}', '會飛的魚,小小雪,茉莉香果果');
INSERT INTO `student` VALUES (2, '小明', '13222222222,13333333333,15777777777', '{\"province\":\"廣東省\",\"city\":\"深圳市\",\"district\":\"南山區\"}', '會飛的魚2,小小雪2,茉莉香果果2');

SET FOREIGN_KEY_CHECKS = 1;

xml方式

在pom.xml添加mybatis,druid,mysql驅動配置

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

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

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>
    
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

在application.yml中配置mybatis

# 使用druid數據源
spring:
    datasource:
        druid:
          driver-class-name: com.mysql.jdbc.Driver
          filters: stat
          maxActive: 20
          initialSize: 1
          maxWait: 60000
          minIdle: 1
          timeBetweenEvictionRunsMillis: 60000
          minEvictableIdleTimeMillis: 300000
          validationQuery: select 'x'
          testWhileIdle: true
          testOnBorrow: false
          testOnReturn: false
          poolPreparedStatements: true
          maxOpenPreparedStatements: 20
          db-type: com.alibaba.druid.pool.DruidDataSource
    thymeleaf:
      cache: false

mybatis:
  type-handlers-package:  com.tiankonglanlande.cn.springboot.mybatis.typehandler
  mapperLocations: classpath:mapper/**.xml
  typeAliasesPackage:  com.tiankonglanlande.cn.springboot.mybatis.bean
  # 開啓自動映射
  configuration:
    map-underscore-to-camel-case: true
    lazy-loading-enabled: false
    auto-mapping-behavior: full

數據庫信息相關配置

spring.datasource.url = jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding-utf8&allowMultiQueries=true
spring.datasource.username= root
spring.datasource.password= root

啓動文件相關配置

@SpringBootApplication
@MapperScan("com.tiankonglanlande.cn.springboot.mybatis.dao")
public class MybatisDruidApplication {

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

說明:@MapperScan掃描注入指定的包名下Mapper接口注入容器

編寫數據庫表對應的Student實體類

/**
 * 學生實體類
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Student implements Serializable {

    private String id;
    private String name;
    private String parentPhone;
    private String city;
    private String netName;
}

編寫StudentDao Mapper接口

public interface StudentDao {

    /**
     * 查詢所有的學生信息
     * @return
     */
    List<Student> selectStudentList();
    
}

編寫StudentDao.xml 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.tiankonglanlande.cn.springboot.mybatis.dao.StudentDao" >

    <select id="selectStudentList" resultType="Student">
        SELECT * FROM student
    </select>

</mapper>

編寫StudentService

@Service
public class StudentService {
    @Autowired
    private StudentDao studentDao;
    public List<Student> selectStudentList(){
        return studentDao.selectStudentList();
    }
}

編寫StudentController

@RestController
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/students")
    public List<Student> selectStudentList(){
        List<Student> students = studentService.selectStudentList();
        return students;
    }
}

在瀏覽器訪問:http://localhost:8080/students得到結果

[
  {
    "id": "1",
    "name": "小英",
    "parentPhone": "13222222222,13333333333,15777777777",
    "city": "{\"province\":\"廣東省\",\"city\":\"深圳市\",\"district\":\"南山區\"}",
    "netName": "會飛的魚,小小雪,茉莉香果果"
  },
  {
    "id": "2",
    "name": "小明",
    "parentPhone": "13222222222,13333333333,15777777777",
    "city": "{\"province\":\"廣東省\",\"city\":\"深圳市\",\"district\":\"南山區\"}",
    "netName": "會飛的魚2,小小雪2,茉莉香果果2"
  }
]

使用純註解方式

StudentDao添加方法selectStudentListByAnnotation

    @Select("SELECT * FROM student")
    List<Student> selectStudentListByAnnotation();

StudentService添加方法selectStudentListByAnnotation

public List<Student> selectStudentListByAnnotation(){
        return studentDao.selectStudentListByAnnotation();
    }

StudentController調用

@RequestMapping("/students2")
    public List<Student> selectStudentListByAnnotation(){
        List<Student> students = studentService.selectStudentListByAnnotation();
        return students;
    }

在瀏覽器訪問:http://localhost:8080/students得到與xml訪問相同的結果

[
  {
    "id": "1",
    "name": "小英",
    "parentPhone": "13222222222,13333333333,15777777777",
    "city": "{\"province\":\"廣東省\",\"city\":\"深圳市\",\"district\":\"南山區\"}",
    "netName": "會飛的魚,小小雪,茉莉香果果"
  },
  {
    "id": "2",
    "name": "小明",
    "parentPhone": "13222222222,13333333333,15777777777",
    "city": "{\"province\":\"廣東省\",\"city\":\"深圳市\",\"district\":\"南山區\"}",
    "netName": "會飛的魚2,小小雪2,茉莉香果果2"
  }
]

解決上面返回json數據的問題

從上面json的數據可以看出parentPhone和netName是多條數據通過逗號拼接成的一個字段,還有city是json字符串組成的文本
這樣前端拿到數據可能還需要進行處理成集合再遍歷出來;city是一個json字符串文本,要想轉化成json還需要一番周折,
那麼作爲認真負責的後臺開發的我們可以使用Mybatis的TypeHandler將parentPhone和netName轉化成集合,將city轉化成標準的json方便前端綁定數據。

處理逗號拼接的字符串爲集合

首先我們看之前在application.yml中配置mybatis的一段代碼

mybatis:
  type-handlers-package:  com.tiankonglanlande.cn.springboot.mybatis.typehandler

說明:這一段代碼會掃描com.tiankonglanlande.cn.springboot.mybatis.typehandler包下面的TypeHandler注入到spring容器

修改一下Student實體屬性爲集合

/**
 * 學生實體類
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Student implements Serializable {

    private String id;
    private String name;
    private String[] parentPhone;//此處修改爲數組對象
    private String city;
    private String[] netName;//此處修改爲數組對象
}

自定義typehandler

/**
 * 字符串轉int數組
 */
public class StringArrayTypeHandler extends BaseTypeHandler<String[]>{
    private static final String delimiter=",";

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String[] strings, JdbcType jdbcType) throws SQLException {
        List<String> list=new ArrayList<>();
        for (String item:strings){
            list.add(String.valueOf(item));
        }
        preparedStatement.setString(i,String.join(delimiter,list));
    }

    @Override
    public String[] getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String str=resultSet.getString(s);
        if (resultSet.wasNull()){
            return null;
        }
        return str.split(delimiter);
    }


    @Override
    public String[] getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String str= resultSet.getString(i);
        if (resultSet.wasNull()){
            return null;
        }
        return str.split(delimiter);
    }

    @Override
    public String[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String str= callableStatement.getString(i);
        if (callableStatement.wasNull()){
            return null;
        }
        return str.split(delimiter);
    }
}

說明:setNonNullParameter方法會在保存數據庫之前執行,我們在此方法將保存的數組使用逗號拼接還原數據庫存儲方式
其他方法是從數據庫取出數據時mybatis將把數據映射成實體類執行,此時我們將逗號拼接的字符串轉換爲數組形式

驗收逗號拼接字符串轉換爲數組成果

瀏覽器輸入http://localhost:8080/students可以看到原先逗號拼接的字符串已經轉換爲集合對象

[
  {
    "id": "1",
    "name": "小英",
    "parentPhone": [
      "13222222222",
      "13333333333",
      "15777777777"
    ],
    "city": "{\"province\":\"廣東省\",\"city\":\"深圳市\",\"district\":\"南山區\"}",
    "netName": [
      "會飛的魚",
      "小小雪",
      "茉莉香果果"
    ]
  },
  {
    "id": "2",
    "name": "小明",
    "parentPhone": [
      "13222222222",
      "13333333333",
      "15777777777"
    ],
    "city": "{\"province\":\"廣東省\",\"city\":\"深圳市\",\"district\":\"南山區\"}",
    "netName": [
      "會飛的魚2",
      "小小雪2",
      "茉莉香果果2"
    ]
  }
]

解決最後一個問題:將city轉化成標準的json方便前端綁定數據

定義CityBean


@Data
@AllArgsConstructor
@NoArgsConstructor
public class CityBean implements Serializable{
    private String province;
    private String city;
    private String district;
}

修改Student將CityBean作爲他的屬性


/**
 * 學生實體類
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Student implements Serializable {

    private String id;
    private String name;
    private String[] parentPhone;//此處修改爲數組對象
    private CityBean city;//修改爲CityBean類
    private String[] netName;//此處修改爲數組對象
}

定義JsonCityBeanTypeHandler


public class JsonCityBeanTypeHandler extends BaseTypeHandler<CityBean> {
    public ObjectMapper objectMapper=new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, CityBean t, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i,objectMapper.writeValueAsString(t));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public CityBean getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String str=resultSet.getString(s);
        if (resultSet.wasNull()){
            return null;
        }
        return getBean(str);
    }

    @Override
    public CityBean getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }

    @Override
    public CityBean getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }

    private CityBean getBean(String str){
        if (StringUtils.isEmpty(str))
            return null;
        try {
            return objectMapper.readValue(str,CityBean.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

如果是存儲的是json集合字符串可以這樣

修改student表添加一個visited字段(數據隨便插入的不要當真哈!)


alter table student add visited varchar(256) COMMENT '去過的地方jsonarray存儲[{"province":"廣東省","city":"深圳市","district":"南山區"}]';
UPDATE student SET visited='[{"province":"四川省","city":"深圳市","district":"南山區"}]' WHERE id=1;
UPDATE student SET visited='[{"province":"四川省","city":"深圳市","district":"南山區"},{"province":"廣東省","city":"成都市","district":"青羊區"}]' WHERE id=2;

定義VisitedBean

/**
 * 去過的地方
 */
public class VisitedBean extends CityBean{

}

定義JsonListTypeHandler


/**
 * json集合字符串轉集合
 * @param <T>
 */
public class JsonListTypeHandler<T> extends BaseTypeHandler<List<T>> {
    public static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,  List<T> parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, objectMapper.writeValueAsString(parameter));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String str = rs.getString(columnName);
        if (rs.wasNull())
            return null;

        return getBeanList(str);
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String str = rs.getString(columnIndex);
        if (rs.wasNull())
            return null;

        return getBeanList(str);
    }

    @Override
    public List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String str = cs.getString(columnIndex);
        if (cs.wasNull())
            return null;

        return getBeanList(str);
    }

    private List<T> getBeanList(String str) {
        if (StringUtils.isEmpty(str)){
            return null;
        }
        try {
            List<T> beanList =objectMapper.readValue(str,new TypeReference<List<T>>(){});
            return beanList;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

測試結果,瀏覽器輸入:http://localhost:8080/students
結果如下:

[
  {
    "id": "1",
    "name": "小英",
    "parentPhone": [
      "13222222222",
      "13333333333",
      "15777777777"
    ],
    "city": {
      "province": "廣東省",
      "city": "深圳市",
      "district": "南山區"
    },
    "visited": [
      {
        "province": "四川省",
        "city": "深圳市",
        "district": "南山區"
      }
    ],
    "netName": [
      "會飛的魚",
      "小小雪",
      "茉莉香果果"
    ]
  },
  {
    "id": "2",
    "name": "小明",
    "parentPhone": [
      "13222222222",
      "13333333333",
      "15777777777"
    ],
    "city": {
      "province": "廣東省",
      "city": "深圳市",
      "district": "南山區"
    },
    "visited": [
      {
        "province": "四川省",
        "city": "深圳市",
        "district": "南山區"
      },
      {
        "province": "廣東省",
        "city": "成都市",
        "district": "青羊區"
      }
    ],
    "netName": [
      "會飛的魚2",
      "小小雪2",
      "茉莉香果果2"
    ]
  }
]

源碼下載鏈接

作者:天空藍藍的,版權所有,歡迎保留原文鏈接進行轉載:)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章