【SpringBoot】 六、MyBatis的集成、MySQL的配置

在进行MyBatis的集成前,请确保安装了MySQL

 

【注解方式】

 

一、从https://start.spring.io/ 下载项目下来

将压缩包解压,在IDAE中导入(File -> New -> Project From Exsiting Source -> 选择 pom.xml 文件)

 

二、在pom.xml中引入依赖

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

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

【注意】 这里用的mysql-connector的版本要与你安装的的MySQL的版本要一致!!否则运行会报错!!

三、添加配置到application.properties (包括MySQL的配置)

spring.datasource.url=jdbc:mysql://localhost:3306/data01?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

其中 //localhost:3306/data01

3306是MySQL的端口号,data01是自己的数据库(下面用navicat说明)

# SpringBoot 2.x 默认配置的数据连接池是 hikari
# 也可以自己配置阿里的druid,不过要额外在pom添加依赖 

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

 

		<!-- druid-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.19</version>
		</dependency>

 

root  和 password 是自己MySQL的用户名和密码,要填对

 

四、在Mysql中创建User表,包含id(BIGINT)、name(VARCHAR)、age(INT)字段。

同时,在包entity创建映射对象User

package com.example.demo3.entity;

public class User {
    private Integer id;
    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public User() {

    }

    public User(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

 

五、在包mapper中创建User映射的操作UserMapper,实现插入和查询操作

package com.example.demo3.mapper;

import com.example.demo3.entity.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Service;

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM USER WHERE id = #{name}")
    User findByName(@Param("name") String name);

    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

    @Update("UPDATE user SET age=#{age} , name=#{name} WHERE id=#{id}")
    void update(User user);

    @Delete("DELETE FROM user WHERE id =#{id}")
    void delete(Integer id);

}

 

六、在controller包中创建 MyController

package com.example.demo3.controller;

import com.example.demo3.entity.User;
import com.example.demo3.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/mapper")
    public String function(){
        userMapper.insert("AAAB", 21);
        User u = userMapper.findByName("AAAB");
        return u.toString();
    }

}

 

注意:如果 

@Autowired
private UserMapper userMapper; 

这里报红线,就走下面的流程。

File -> Setting ->

 

接着启动项目,打开网页输入localhost:8080/mapper

或者使用PostMan,发起GET请求

 

七、返回结果的绑定

而对于“查”操作,我们往往需要进行多表关联,汇总计算等操作,那么对于查询的结果往往就不再是简单的实体对象了,往往需要返回一个与数据库实体不同的包装类,那么对于这类情况,就可以通过@Results@Result注解来进行绑定,具体如下:

@Results({
    @Result(property = "name", column = "name"),
    @Result(property = "age", column = "age")
})
@Select("SELECT name, age FROM user")
List<User> findAll();

在上面代码中,@Result中的property属性对应User对象中的成员名,column对应SELECT出的字段名。在该配置中故意没有查出id属性,只对User对应中的name和age对象做了映射配置

 

参考博文:http://blog.didispace.com/springbootmybatis/

 

【配置XML方式】

以上介绍的是注解的方式,这里再推荐一篇配置XML方式集成MyBaits的

https://www.jianshu.com/p/34bfce24b115

 

一、新建工程并创建数据表与映射类

参考上面的一、二、三、四步骤

 

二、在包dao中创建User映射的操作UserDAO

package com.example.demo3.dao;

import com.example.demo3.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface UserDAO {
    User getUserById(int id);
    void addUser(@Param("name")String name, @Param("age")int age);
    void upDataUser(@Param("id")int id,@Param("name")String name,@Param("age")int age);
    void deleteUser(int id);
}

包括两位及以上参数时,需要加上注解@Param,否则在下面的那个UserDAO.xml文件中无法识别参数

 

三、编写UserDAO的xml配置文件

根据UserDAO的文件位置来创建同路径的xml文件

右键包resources,new一个新的Directory,取名为com

接着又在新建的com上右键新建目录example,接着再右键新建目录demo3,再右键新建目录dao,最后创建文件UserDAO.xml 

 UserDAO.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.demo3.dao.UserDAO">
    <sql id="table">user</sql>
    <sql id="selectFields">id,name,age</sql>

    <select id="getUserById" resultType="com.example.demo3.entity.User">
        SELECT
        <include refid="selectFields"/>
        FROM
        <include refid="table"/>
        WHERE
        id = #{id}
    </select>

    <insert id="addUser" parameterType="com.example.demo3.entity.User">
        INSERT INTO
        <include refid="table"></include>
        (name,age)
        VALUES
        (#{name},#{age})
    </insert>

    <update id="upDataUser" parameterType="com.example.demo3.entity.User">
        UPDATE
        <include refid="table"></include>
        SET
        name = #{name},age = #{age}
        WHERE
        id = #{id}
    </update>

    <delete id="deleteUser" parameterType="com.example.demo3.entity.User">
        DELETE FROM
        <include refid="table"></include>
        WHERE
        id = #{id}
    </delete>

</mapper>

 

四、创建mybatis-config.xml(无特殊要求,这部分可以跳过)

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>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>
    </settings>
    <!-- Continue going here -->
</configuration>

这其中有个需要注意的点:如果你在表里建立的参数是以下划线命名的,当你从数据库中取数据出来需要转成实体类的驼峰式命名属性,则需要在配置文件中写上

<setting name="mapUnderscoreToCamelCase" value="true"/>

接着添加到 application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/data01?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis.config-location=classpath:mybatis-config.xml
mybatis.type-aliases-package=com.example.demo3.entity
mybatis.mapper-locations=classpath:com/example/demo3/dao/*.xml

yml格式

mybatis:
  type-aliases-package: com.xilo.shiro.entity
  mapper-locations: classpath:com/example/bt/dao/*.xml
  config-location: classpath:mybatis-config.xml

这样就完成了MyBatis的配置

 

五、编写service

package com.example.demo3.service;

import com.example.demo3.dao.UserDAO;
import com.example.demo3.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MyService {
    @Autowired
    UserDAO userDAO;

    public String function1() {
        User user = userDAO.getUserById(2);
        return user.toString();
    }

    public void function2() {
        userDAO.addUser("mary",15);
    }

    public void function3() {
        userDAO.upDataUser(2,"bob-----------",20);
    }

    public void function4() {
        userDAO.deleteUser(3);
    }
}

 

五、编写controller

package com.example.demo3.controller;

import com.example.demo3.entity.User;
import com.example.demo3.service.MyService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
public class MyController {

    @Resource
    MyService myService;

    @GetMapping("/mapper")
    public String getMapper() {
        myService.function2();
        myService.function3();
        myService.function4();
        return myService.function1();
    }

}

启动项目即完成

 

关于配置文件的标签

<resuletMap>

<resultMap  id="userMap" type="User">
    <!-- property 是实体类User的属性   column 是数据表user的字段  -->
    <result property="" column=""  />
    <result property="" column=""  />
    <result property="" column=""  />
</resultMap>

resultMap 元素用来描述如何将结果集映射到 Java 对象,使用 resultMap 对列表展示所需的必要字段来进行自动映射,特别是当数据库的字段名和实体类 POJO 中的属性名不一致的情况下,比如角色名称,字段名/列名 column 是 roleName,而 User 对象的属性名则为 userRoleName ,此时就需要做映射。

  resultMap 元素的属性值和子节点

     id 属性:唯一标识,此 id 值用于 select 元素 resultMap 属性的引用。

     type 属性:表示该 resultMap 的映射结果类型。

       result 子节点:用于标识一些简单属性,其中 column 属性表示从数据库中查询的字段名或别名, property 属性则表示查询出来的字段对应的值赋给实体对象的哪个属性。

该段原文出自:https://www.cnblogs.com/wxdestiny/p/9749482.html

注意:resultMap中可以只手动设置实体类字段和数据表之间不能自动转换字段的映射关系,也就是说resultMap不代表全部的查询的映射结果,还有部分自动转换的映射结果仍然会放进实体类中。

例如:

     可自动转化       name  ->  name 

     不能自动转换   roleName  ->  userRoleName  ,这时就需要resultMap手动设置映射关系

 

SQL语句的参数类型

parameterType   入参格式
resultType     返回参数的格式
resultMap      返回参数的自定义格式(配合<resultMap>标签使用)

 

---------------------------------------------------------------------2020.10.29------------------------------------------------------------

两个月后回顾之前写的玩意,发现有很多瑕疵,比如函数名还是function这种意义不明的东西。。

下面贴一下现在Mybaits的代码,包括了一些命名规范以及使用习惯,可以给大家参考参考,包括在实际的开发当中,一搬是会传一整个对象进行数据操作的

 

  • 工程目录

 

  • 文件内容

MyTable.java

package com.example.demo3.dao;

public class MyTable {
    private String id;
    private String name;
    private String phone;
    private String date;
    private String status;
    private String user_img;

    public String getUser_img() {
        return user_img;
    }

    public void setUser_img(String user_img) {
        this.user_img = user_img;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "MyTableDTO{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                ", date='" + date + '\'' +
                ", status='" + status + '\'' +
                ", user_img='" + user_img + '\'' +
                '}';
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

 

MyTableMapper.java

package com.example.demo3.mapper;

import com.example.demo3.dao.MyTable;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface MyTableMapper {
    MyTable getTableById(@Param("id") String id);
    List<MyTable> getAll();
    int updateTable(MyTable myTableDTO);
    int deleteTable(MyTable myTableDTO);
    int addTable(MyTable myTableDTO);
    List<MyTable> queryTable(MyTable myTableDTO);
}

 

MyTableMapper.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.demo3.mapper.MyTableMapper">

    <select id="getTableById" resultType="com.example.demo3.dao.MyTable">
        SELECT * FROM mytable02 WHERE id = #{id}
    </select>

    <select id="getAll" resultType="com.example.demo3.dao.MyTable">
            SELECT * FROM mytable02
    </select>

    <update id="updateTable" parameterType="com.example.demo3.dao.MyTable">
            UPDATE mytable02
            <trim prefix="set" suffixOverrides=",">
                <if test="name != null and name != ''">name=#{name},</if>
                <if test="phone != null and phone != ''">phone=#{phone},</if>
                <if test="user_img != null and user_img != ''">user_img=#{user_img},</if>
            </trim>
            WHERE id = #{id}
    </update>

    <delete id="deleteTable" parameterType="com.example.demo3.dao.MyTable">
            DELETE FROM mytable02
            WHERE id = #{id}
    </delete>

    <insert id="addTable" parameterType="com.example.demo3.dao.MyTable">
            INSERT INTO mytable02
            <trim prefix="(" suffix=')' suffixOverrides=",">
                <if test="id != null and id != ''">id,</if>
                <if test="name != null and name != ''">name,</if>
                <if test="phone != null and phone != ''">phone,</if>
                <if test="user_img != null and user_img != ''">user_img,</if>
            </trim>

            <trim prefix="values (" suffix=")" suffixOverrides=",">
                <if test="id != null and id != ''">#{id},</if>
                <if test="name != null and name != ''">#{name},</if>
                <if test="phone != null and phone != ''">#{phone},</if>
                <if test="user_img != null and user_img != ''">#{user_img},</if>
            </trim>
    </insert>

    <select id="queryTable" parameterType="com.example.demo3.dao.MyTable" resultType="com.example.demo3.dao.MyTable">
            SELECT * FROM mytable02
            WHERE
            <trim >
                <if test="id != null and id != ''">id=</if>
                <if test="name != null and name != ''">name=</if>
                <if test="phone != null and phone != ''">phone=</if>
            </trim>

            <trim>
                <if test="id != null and id != ''">#{id}</if>
                <if test="name != null and name != ''">#{name}</if>
                <if test="phone != null and phone != ''">#{phone}</if>
            </trim>
    </select>

</mapper>

 

使用:

service层

package com.example.demo3.service;

import com.example.demo3.dao.MyTable;
import com.example.demo3.mapper.MyTableMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MyService {
    @Resource
    MyTableMapper myTableMapper;

    public MyTable TableFindById(String id){
        return myTableMapper.getTableById(id);
    }

    public List<MyTable> TableFindAll(){
        return myTableMapper.getAll();
    }

    public String TableEdit(MyTable myTableDTO){
        int i = myTableMapper.updateTable(myTableDTO);
        if(i==0){   //如果i的值为0,意味着此次操作影响了0条数据(即操作失败)
            System.out.println("false");
            return "false";
        }
        System.out.println("true");
        return "true";
    }

    public String TableDelete(MyTable myTableDTO){
        int i = myTableMapper.deleteTable(myTableDTO);
        if(i==0){
            System.out.println("false");
            return "false";
        }
        System.out.println("true");
        return "true";
    }

    public String TableAdd(MyTable myTableDTO){
        System.out.println("there are add");
        int i = myTableMapper.addTable(myTableDTO);
        if(i==0){
            System.out.println("false");
            return "false";
        }
        System.out.println("true");
        return "true";
    }

    public List<MyTable> TableQuery(MyTable myTableDTO){
        List<MyTable> list = myTableMapper.queryTable(myTableDTO);
        return list;
    }

}

 

【坑1】

如果启动项目之后报错

### Error querying database.  Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
### The error may exist in com/example/bt/dao/UserMapper.xml
### The error may involve com.example.bt.dao.UserMapper.getAll
### The error occurred while executing a query
### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long] with root cause

java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long

那可能是数据库版本与mysql-connector.jar包的版本不兼容造成的。本人用的是Mysql8.0.12免安装版本,出现问题时的jar包版本为5.1.26,更换为5.1.47后解决了该问题。希望能够帮助到遇到这类问题的朋友。

转自:http://www.mamicode.com/info-detail-2583387.html

 

【坑2】

如果启动项目之后报错找不到相应的mapper,则可能是没有添加配置

mybatis.type-aliases-package=com.example.demo3.entity
mybatis.mapper-locations=classpath:com/example/demo3/dao/*.xml

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值