• SpringBoot入门之基于XML的Mybatis


    上一博客介绍了下SpringBoot基于注解引入Mybatis,今天介绍基于XML引入Mybatis。还是在上一篇demo的基础上进行修改.

    一、Maven引入

    这个与上一篇的一样,需要引入mybatis相关和mysql相关的,这里就不多说。

    二、创建Model

    这里还是用User这个model,与上一篇的一样,略过。

    三、创建Mapper

    在基于注解引入mybatis时,创建mapper将model与数据库操作进行联系,在mapper中使用注解来进行配置sql,那如果使用xml进行配置的话,这些注解就不能再用了。下面的代码还是在上一mapper基础上进行了下修改。这里注释了注解部分,就是单纯的接口。

    package com.example.mapper;
    import java.util.List;
    
    //import org.apache.ibatis.annotations.Delete;
    //import org.apache.ibatis.annotations.Insert;
    //import org.apache.ibatis.annotations.Result;
    //import org.apache.ibatis.annotations.Results;
    //import org.apache.ibatis.annotations.Select;
    //import org.apache.ibatis.annotations.Update;
    
    import com.example.model.*;
    
    public interface  UserMapper {
    
    //    @Select("SELECT * FROM user")
    //
    //    @Results({
    //
    //        @Result(property = "Sex",  column = "sex", javaType = UserSexEnum.class),
    //
    //        @Result(property = "Name", column = "name")
    //
    //    })
    
        List<User> getAll();
    
        
    
    //    @Select("SELECT * FROM user WHERE id = #{id}")
    //
    //    @Results({
    //
    //        @Result(property = "Sex",  column = "sex", javaType = UserSexEnum.class),
    //
    //        @Result(property = "Name", column = "name")
    //
    //    })
    
        User getOne(int id);
    
    
    
    //    @Insert("INSERT INTO user(name,age,sex) VALUES(#{name}, #{age}, #{sex})")
    
        void insert(User user);
    
    
    
    //    @Update("UPDATE user SET name=#{userName},age=#{age} WHERE id =#{id}")
    
        void update(User user);
    
    
    
    //    @Delete("DELETE FROM user WHERE id =#{id}")
    
        void delete(int id);
    }

    四、配置扫描

    创建的mapper怎么让系统知道mapper放在哪里呢?于是有了@MapperScan注解。这个与上一篇一样。

    package com.example.demo;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    @MapperScan("com.example.mapper")
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    }
    View Code

    五、创建Controller

    这里也是与上一篇一样。

    package com.example.demo;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import com.example.mapper.UserMapper;
    import com.example.model.User;
    import com.example.model.UserSexEnum;
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
        
        @Autowired
        private UserMapper userMapper;
        
        @RequestMapping(value = "/alluser.do",method = RequestMethod.GET)
        public String getallusers(Model model) {
           List<User> users=userMapper.getAll();
           model.addAttribute("users", users);
           return "userlist";
        }
        @RequestMapping(value = "/insert.do",method = RequestMethod.GET)
        public String adduser(Model model) {
           User user=new User();
           user.setName("cuiyw");
           user.setAge(27);
           user.setSex(UserSexEnum.MAN);
                    
           userMapper.insert(user);
           List<User> users=userMapper.getAll();
           model.addAttribute("users", users);
           return "userlist";
        }
    }
    View Code

    六、数据库配置

    今天还报时区的错误,这里改变了下数据库的配置,在url中增加了编码和时区

    spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
    #spring.datasource.url = jdbc:mysql://localhost:3306/mybatis
    spring.datasource.url =jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    spring.datasource.username = root
    spring.datasource.password = 123456

    七、创建xml映射关系

    如果是使用注解的话在第四步创建mapper的时候直接把sql也配置进来了,但是这里是把sqp配置是注释掉的,既然注释掉了那肯定得有另外一种形式来体现出来不是。于是这里还需要新增一个mapper.xml用来配置sql.

    <?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.mapper.UserMapper" >
        <resultMap id="BaseResultMap" type="com.example.model.User" >
            <id column="id" property="id" jdbcType="NUMERIC" />
            <result column="name" property="Name" jdbcType="VARCHAR" />
            <result column="age" property="Age" jdbcType="NUMERIC" />
            <result column="sex" property="Sex" javaType="com.example.model.UserSexEnum"/>
           
        </resultMap>
        
        <sql id="Base_Column_List" >
            id, name, age, sex
        </sql>
    
        <select id="getAll" resultMap="BaseResultMap"  >
           SELECT 
           <include refid="Base_Column_List" />
           FROM user
        </select>
    
        <select id="getOne" parameterType="java.lang.Integer" resultMap="BaseResultMap" >
            SELECT 
           <include refid="Base_Column_List" />
           FROM user
           WHERE id = #{id}
        </select>
    
        <insert id="insert" parameterType="com.example.model.User" >
           INSERT INTO 
                   user
                   (name,age,sex) 
               VALUES
                   (#{Name}, #{Age}, #{Sex})
        </insert>
        
        <update id="update" parameterType="com.example.model.User" >
           UPDATE 
                   user
           SET 
               <if test="Name != null">name = #{Name},</if>
               <if test="Age != null">age = #{Age}</if>
               <if test="Sex != null">sex = #{Sex}</if>
           WHERE 
                   id = #{id}
        </update>
        
        <delete id="delete" parameterType="java.lang.Integer" >
           DELETE FROM
                    user
           WHERE 
                    id =#{id}
        </delete>
    
    </mapper>
    View Code

    这里又新建了一个配置文件用来配置mybatis其他属性。

    <?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>
        <typeAliases>
            <typeAlias alias="Integer" type="java.lang.Integer" />
            <typeAlias alias="Long" type="java.lang.Long" />
            <typeAlias alias="HashMap" type="java.util.HashMap" />
            <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
            <typeAlias alias="ArrayList" type="java.util.ArrayList" />
            <typeAlias alias="LinkedList" type="java.util.LinkedList" />
        </typeAliases>
    </configuration>
    View Code

    这些新增之后还不算完,新增放在那系统也不知道呀,需要把这些新建的xml配置到mybatis中,让它起作用。所以需要在application.properties配置mybatis的一些属性。设置配置文件和映射文件的位置.

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

    八、测试

    这里创建页面显示还是与上一篇一样,直接略,还是打开url:http://localhost:8080/user/alluser.do能显示列表,输入url:http://localhost:8080/user/insert.do时列表增加一行信息显示。这里效果图与上一篇也是一样的。这里也不上测试结果的图了,上一张整个项目的目录图。

  • 相关阅读:
    241. Different Ways to Add Parentheses
    332. Reconstruct Itinerary
    [LeetCode] 19. Remove Nth Node From End of List Java
    [LeetCode] 16. 3Sum Closest Java
    [LeetCode] 15. 3Sum Java
    [LeetCode] 11. Container With Most Water Java
    [LeetCode] 4. Median of Two Sorted Arrays
    [LeetCode] 3.Longest Substring Without Repeating Characters
    [LeetCode] 50. Pow(x, n) Java
    [LeetCode] 45. Jump Game II Java
  • 原文地址:https://www.cnblogs.com/5ishare/p/9296936.html
Copyright © 2020-2023  润新知