• spring boot mysql和mybatis


    1 选择mysql驱动

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

    2 选择mybatis orm

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

    3 配置mysql和mybatis

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

    mybatis.mapperLocations=classpath:mapper/*.xml

    4 dao dao和Mapper xml

    它们是一一对应的,Mapper xml中负责sql的编写,dao负责在业务中执行相应的操作。

    package com.hello.springboot.dao;
    import com.hello.springboot.entity.User;
    import java.util.List;
    public interface UserDao {
        List<User> findAll();
        User findById(Long id);
        void insert(User user);
        void update(User user);
        void delete(Long id);
    }

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <!--namespace是命名空间,是mapper接口的全路径-->
    <mapper namespace="com.hello.springboot.dao.UserDao">

    <!--resultMap – 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象--> <resultMap id="userResultMap" type="com.hello.springboot.entity.User"> <id property="name" column="username"></id> </resultMap> <!--sql – 可被其他语句引用的可重用语句块--> <sql id="colums"> id,username,age,pwd </sql> <select id="findAll" resultMap="userResultMap"> select <include refid="colums" /> from user </select> <select id="findById" resultMap="userResultMap"> select <include refid="colums" /> from user where id=#{id} </select> <insert id="insert" parameterType="com.hello.springboot.entity.User" > INSERT INTO user (username,age,pwd) VALUES (#{name}, #{age}, #{pwd}) </insert> <update id="update" parameterType="com.hello.springboot.entity.User" > UPDATE users SET <if test="username != null">username = #{username},</if> <if test="pwd != null">pwd = #{pwd},</if> username = #{username} WHERE id = #{id} </update> <delete id="delete" parameterType="java.lang.Long" > DELETE FROM user WHERE id =#{id} </delete> </mapper>

    三点要注意:

    第一,注意,Mapper xml中的namespace就是对应的dao接口的完整路径名;

    第二,Mapper接口中的方法的名字要和Mapper xml中操作的名字一样;

    第三,注意参数;

    5 在代码中使用dao层的接口

    给dao类加上下面的注解,然后就可以像普通的类一样使用dao对象。

    @Repository
    @Mapper

    6 关于dao接口中函数的返回值

    第一,调用dao接口时用try catch来进行异常处理,如果出现异常会抛出异常;

    第二,在mapper.xml中指定返回值的类型即可,这个类型保持和dao接口中函数的类型一致;

  • 相关阅读:
    P1005 矩阵取数
    [BZOJ2662][BeiJing wc2012]冻结
    [BZOJ1191]超级英雄Hero
    [bzoj1008] 越狱
    [bzoj1001]狼抓兔子 最小割
    网络流24题——负载平衡问题
    分形小山
    可并堆——左偏树、斜堆
    NOIP最优贸易
    洛谷P2073送花
  • 原文地址:https://www.cnblogs.com/hustdc/p/10064792.html
Copyright © 2020-2023  润新知