Spring Boot/ORM框架——Mybatis的增删改查

2020-04-07  本文已影响0人  水煮蛋呢

一.ORM:对象关系模型

二.Spring 使用mybatis的步骤——XML方式:

先在数据库创建表,连接好数据库,完成增删改查功能。

1.mybatis的依赖和配置:

<!--依赖-->
 <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
 </dependency>

#配置
#公共属性文件的配置地址
#mybatis.config-location=classpath:mybatis/mybatis-config.xml
#映射文件通配符的配置地址
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
#扫描别名包,和注解@Alias联用,暂时没用到
mybatis.type-aliases-package=com.niit.mybatisdemo.model
#表的下划线与类的驼峰式对应
mybatis.configuration.map-underscore-to-camel-case=true

2.创建实体类和接口:

@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Message {
    private Integer msgId;
    private String msgText;
    private String msgSummary;
}
@Mapper
@Repository
public interface MessageMapper {
    List<Message> selectAll();
    Message selectById(Integer id);
    int insert(Message message);
    int delete(Integer id);
    int update(Message message);
    int updateText(Message message);
    int batchInsert(List<Message> messages);
}

3.表的映射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.niit.mybatisdemo.mapper.MessageMapper">
    <resultMap id="BaseResultMap" type="com.niit.mybatisdemo.model.Message">
        <id column="msg_id" property="msgId" jdbcType="BIGINT"/>
        <result column="msg_text" property="msgText" jdbcType="VARCHAR"/>
        <result column="msg_summary" property="msgSummary" jdbcType="VARCHAR"/>
    </resultMap>

    <sql id="Base_Column_List">
        msg_id,msg_text,msg_summary
    </sql>

    <insert id="insert" parameterType="com.niit.mybatisdemo.model.Message">
        insert into message(msg_text,msg_summary) values (#{msgText},#{msgSummary})
    </insert>

    <select id="selectAll" resultMap="BaseResultMap">
        select * from message
    </select>

    <select id="selectById" parameterType="Integer" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"></include>
        FROM message
        WHERE msg_id=#{msgId}
    </select>

    <delete id="delete" parameterType="Integer">
        DELETE FROM message WHERE msg_id=#{msgId}
    </delete>

    <update id="update" parameterType="com.niit.mybatisdemo.model.Message">
        Update message SET
        <if test="msgText != null"> msg_text=#{msgText},</if>
        <if test="msgSummary != null"> msg_summary=#{msgSummary}</if>
        WHERE msg_id = #{msgId}
    </update>

    <update id="updateText" parameterType="com.niit.mybatisdemo.model.Message">
        UPDATE message
        <set>
            <if test="msgText != null and msgText != ''"> msg_text=#{msgText}</if>
            <if test="msgSummary != null and msgSummary != ''"> msg_summary=#{msgSummary}</if>
        </set>
        WHERE msg_id = #{msgId}
    </update>
    
    <insert id="batchInsert" parameterType="com.niit.mybatisdemo.model.Message">
        INSERT INTO message (msg_text,msg_summary) VALUES
        <foreach collection="list" item="msg" index="index" separator=",">
            (#{msg.msgText},#{msg.msgSummary})
        </foreach>
    </insert>

</mapper>

4.写测试类:

@Slf4j
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class MessageMapperTest {

    @Autowired
    private  MessageMapper messageMapper;

    @Test
    @Order(1)
    public void testInsert(){
        //模拟数据
        Message message = Message.builder().msgText("樱花").msgSummary("春天").build();
        int num = messageMapper.insert(message);
        log.info("插入数据数:{}",num);
    }

    @Test
    @Order(2)
    public void  testSelectAll(){
        List<Message> messages = messageMapper.selectAll();
        if (messages == null){
            log.error("messages为null");
        }else {
            messages.forEach(message -> log.info("查询到的数据:{}",message));
        }
    }


    @Test
    @Order(3)
    public void testSelectById(){
        Message message = messageMapper.selectById(1);
        log.info("id为1的数据:{}",message);
    }

    @Test
    @Order(4)
    public void testDelete(){
        int num = messageMapper.delete(1);
        log.info("删除的数据数:{}",num);
    }

    @Test
    @Order(5)
    public void testUpdate(){
        Message message = Message.builder().msgId(1).msgText("computer").msgSummary("学校").build();
        int num = messageMapper.update(message);
        log.info("更新的数据条数:{}",num);
    }

    @Test
    @Order(6)
    public void testUpdateText(){
        Message message = Message.builder().msgId(1).msgText("hhh").msgSummary("").build();
        int num = messageMapper.updateText(message);
        log.info("更新Text的数据条数:{}",num);
    }


    @Test
    @Order(7)
    public void testBatchInsert(){
        List<Message> messages = new ArrayList<>(Arrays.asList(
                Message.builder().msgText("apple").msgSummary("水果").build(),
                Message.builder().msgText("orange").msgSummary("水果").build()));
        int num = messageMapper.batchInsert(messages);
        log.info("插入的数据条数:{}",num);
    }
}

5.结果:

三.Spring 使用mybatis的步骤——注解方式:

只需要将上面XML方式中的【3.表的映射xml文件配置】删除,并在接口中添加代码就可以了,运行结果一样。

@Mapper
@Repository
public interface MessageMapper {
    @Select("select * from message")
   List<Message> selectAll();

   @Select("select * from message where msg_id=#{msgId}")
   Message selectById(Integer id);


   @Insert("insert into message (msg_text,msg_summary) values (#{msgText},#{msgSummary})")
   int insert(Message message);

   @Insert({"<script>" +
           "insert into message (msg_text,msg_summary) values" +
           "<foreach collection = 'list' item='msg' index='index' separator = ','>" +
           "(#{msg.msgText},#{msg.msgSummary})" +
           "</foreach>" +
           "</script>"})
   int batchInsert(List<Message> messages);

   @Delete("delete from message where msg_id=#{msgId}")
   int delete(Integer id);

   @Update({"<script>" +
           "update message set" +
           "<if test = 'msgText != null'>msg_text = #{msgText}</if>," +
           "<if test = 'msgSummary != null'>msg_summary = #{msgSummary}</if>" +
           "where msg_id = #{msgId}" +
           "</script>"})
   int update(Message message);

   @Update({"<script>" +
           "update message" +
           "<set>" +
           "<if test = 'msgText != null'>msg_text = #{msgText}</if>," +
           "<if test = 'msgSummary != null'>msg_summary = #{msgSummary}</if>" +
           "</set>" +
           "where msg_id = #{msgId}" +
           "</script>"})
   int updateText(Message message);
}

四.Spring 使用mybatis的步骤——辅助工具快速创建方式:

1.安装插件:

MyBatis Generator的运行方法有多种,下面介绍通过Maven插件mybatis-generator-maven-plugin运行。

2.添加并连接数据库和配置mybatis:

我创建了两张表,实现1对多关系,在users表中添加主键

//数据库的表
drop table if exists message;
create table message(
msg_id int not null auto_increment,
msg_text VARCHAR(32) not null,
msg_summary VARCHAR(32) default null,
PRIMARY KEY(msg_id)
)engine=INNODB auto_increment=1 DEFAULT charset=utf8


drop table if exists users;
create table users (
    id bigint auto_increment comment '主键id' primary key,
    user_name     varchar(32)  null comment '用户名',
    sex int(3) not null default 1 comment '性别',
    note varchar(256) null comment '笔记'
)engine = InnoDB default charset = utf8;
spring.datasource.url=jdbc:mysql://localhost:3306/test1?serverTimezone=UTC\
&useUnicode=true&characterEncoding=utf-8&useSSL=true&nullCatalogMeansCurrent = true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# mybatis的配置
mybatis.mapper-locations=classpath*:/mapper/**/*.xml
mybatis.type-aliases-package=com.niit.mybatisgeneratordemo.model
mybatis.configuration.map-underscore-to-camel-case=true

3.添加插件配置:

             <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.4.0</version>
                <configuration>
                    <!--mybatis的代码生成器的配置文件-->
                    <configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
                    <!--允许覆盖生成的文件-->
                    <overwrite>true</overwrite>
                    <!-- 允许移动生成的文件-->
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.19</version>
                    </dependency>
                </dependencies>
            </plugin>

4.在resources下配置Mybatis Generator:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC
        "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 引入配置文件 -->
    <properties resource="application.properties"/>
    <!-- 配置context -->
    <context id="simple" targetRuntime="MyBatis3">
        <plugin type="org.mybatis.generator.plugins.FluentBuilderMethodsPlugin"/>
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"/>

        <commentGenerator>
            <!-- 不希望生成的注释中包含时间戳 -->
            <property name="suppressDate" value="true"/>
        </commentGenerator>

        <!-- 数据库连接 -->
        <jdbcConnection driverClass="${spring.datasource.driver-class-name}"
                        connectionURL="${spring.datasource.url}"
                        userId="${spring.datasource.username}"
                        password="${spring.datasource.password}"/>

        <!-- 数据表对应的model层  -->
        <javaModelGenerator targetPackage="com.niit.mybatisgeneratordemo.model"
                            targetProject="./src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- sql mapper 映射配置文件 -->
        <sqlMapGenerator targetPackage="."
                         targetProject="./src/main/resources/mapper">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- mybatis3中的mapper接口 -->
        <javaClientGenerator type="MIXEDMAPPER"
                             targetPackage="com.niit.mybatisgeneratordemo.mapper"
                             targetProject="./src/main/java">
            <property name="enablePackages" value="true"/>
        </javaClientGenerator>

<!--         数据表生成操作 schema:相当于库名; tableName:表名; domainObjectName:对应的DO -->
<!--        <table tableName="users" domainObjectName="Useusersrs"-->
<!--               enableCountByExample="false" enableUpdateByExample="false"-->
<!--               enableDeleteByExample="false" enableSelectByExample="false"-->
<!--               selectByExampleQueryId="false">-->
<!--        </table>-->

    <table tableName="message" domainObjectName="Message" />
    <table tableName="users" domainObjectName="Users" />
</context>
</generatorConfiguration>

注意:如果您使用的是mysql-connector-java的8.x版,生成器可能会尝试为MySql information schemas中的表生成代码。要禁用此行为,请将属性“nullCatalogMeansCurrent = true”添加到JDBC URL。MySql不能正确支持SQL catalogs和schema。

5.生成时使用插件:

6.项目目录结构图:

上一篇下一篇

猜你喜欢

热点阅读