springboot整合mybatis的xml形式

前言

mybatis開發過程中用到的還是比較多的,之前我用的大多都是註解形式,xml用的不多,所以就用了點時間吧xml格式的也看了下,做了總結在這裏寫下。

開始工作

引入jar包

		<dependency><!-- 引入mybits依賴-->
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency><!-- mysql連接java包 -->
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

配置文件

#驅動名稱
spring.datasource.driverClassName=com.mysql.jdbc.Driver
#url地址
spring.datasource.url=jdbc:mysql://localhost:3306/poetry?useUnicode=true&characterEncoding=utf-8&&serverTimezone=GMT%2B8
#用戶名
spring.datasource.username=root
#密碼
spring.datasource.password=yu123467.

#掃描實體類路徑
mybatis.type-aliases-package=com.xue.mybitsdemo.entity
#映射文件路徑及名稱
mybatis.mapper-locations:classpath:mapper/*Mapper.xml
#mybats配置文件
mybatis.config-location:classpath:config/mybits-config.xml

測試用表建表語局

CREATE TABLE `student` (
	`s_id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
	`s_name` VARCHAR(50) NOT NULL DEFAULT '0' COMMENT '學生姓名',
	`s_age` INT(11) NOT NULL DEFAULT '0' COMMENT '學生年齡',
	`s_sex` VARCHAR(50) NOT NULL DEFAULT '0' COMMENT '學生性別',
	PRIMARY KEY (`s_id`)
)
COMMENT='學生信息表'
ENGINE=InnoDB
;

目錄結構

-- main
	--java
		--com.xue.mybitsdemo
			--dao
				--StudentMapper.class
			--entity
				--StudentEntity.class
			--MybitsdemoApplication.class	
	--resource
		--config
			mybatis-config.xml
		--mapper
			StudentMapper.xml 
		--application.properties

xml格式

mybits-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>
        <!-- 開啓駝峯匹配 -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>

Mapper開發

package com.xue.mybitsdemo.dao;

import com.xue.mybitsdemo.entity.StudentEntity;

import java.util.List;

public interface StudentMapper {
    //根據id獲取一條數據
    StudentEntity getOne(Integer id);

    //根據多條件獲取一條數據
    StudentEntity getOne2(StudentEntity studentEntity);

    //獲取全部數據
    List<StudentEntity> getAll();

    //插入一條數據
    void insert(StudentEntity studentEntity);

    //刪除一條數據
    void deleteOne(Integer id);

    //修改一條數據
    void update(StudentEntity studentEntity);

}

這些接口需要在映射文件中一一實現,可以在類文件上添加@Mapper註解,很多Mapper的話有點麻煩,推薦直接在啓動類那添加。啓動的時候,就去掃描,自動注入了

@SpringBootApplication
@MapperScan(basePackages= {"com.xue.mybitsdemo.dao"})
public class MybitsdemoApplication {

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

}

實體類文件

package com.xue.mybitsdemo.entity;

public class StudentEntity {
    private Integer id;
    private String name;
    private Integer age;
    private String sex;

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

    public StudentEntity(String name, Integer age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    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 String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

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

添加Student的映射文件

<?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.xue.mybitsdemo.dao.StudentMapper">
    <resultMap id="studentMap" type="StudentEntity">
        <id column="s_id" property="id" jdbcType="BIGINT"/>
        <result column="s_name" property="name"/>
        <result column="s_age" property="age"/>
        <result column="s_sex" property="sex"/>
    </resultMap>

    <!--    <insert id="insert" useGeneratedKeys="true"-->
    <!--            keyProperty="id" parameterType="StudentEntity" >-->
    <!--            insert into student (s_name,s_age,s_sex)-->
    <!--            values (#{name},#{age},#{sex})-->
    <!--    </insert>-->
    <insert id="insert" parameterType="StudentEntity">
            insert into student (s_name,s_age,s_sex)
            values (#{name},#{age},#{sex})
    </insert>


    <select id="getAll" resultMap="studentMap">
        select s_id,s_name,s_age,s_sex from student
    </select>

    <select id="getOne" parameterType="Integer" resultMap="studentMap">
        select s_id,s_name,s_age,s_sex from student where s_id = #{id}
    </select>

    <select id="getOne2" parameterType="StudentEntity" resultMap="studentMap">
        select s_id,s_name,s_age,s_sex from student
        <where>
            <if test="id != null">
                s_id=#{id}
            </if>
            <if test="name != null">
                AND s_name=#{name}
            </if>
            <if test="age != null">
                AND s_age=#{age}
            </if>
            <if test="sex != null">
                AND s_sex=#{sex}
            </if>
        </where>
    </select>

    <delete id="deleteOne" parameterType="Integer">
        delete from  student where s_id = #{id}
    </delete>

    <!--    <update id="update" parameterType="StudentEntity">-->
    <!--        update student set s_name = #{name},s_age = #{age},s_sex = #{sex} where s_id=#{id}-->
    <!--    </update>-->

    <update id="update" parameterType="StudentEntity">
        update student
        <set>
            <if test="name != null">s_name=#{name},</if>
            <if test="age != null">s_age=#{age},</if>
            <if test="sex != null">s_sex=#{sex}</if>
        </set>
        where s_id=#{id}
    </update>
</mapper>
xml詳細解釋

resultMap 自定義返回結果。
主要用於轉換字段,當數據庫的字段和實體類的不一致的時候。其中column屬性是數據庫字段,property屬性是實體類的字段。數據庫裏面的是“s_name”字段,實體類的是“name”字段。當然了,還有更簡單的,那就是數據庫查詢的時候直接 select s_name as name from student。 用resultMap 主要是爲了規範

<select><update><delete><insert>中的id屬性值必須和mapper中的方法名完全一致

parameterType 參數類型
namespace命名空間,可以通過此路徑來調用映射文件。

update,getOne2兩個方法,分別用了<where></where>和<set></set>,這兩個用法就是避免了自己在寫部分條件爲空的邏輯處理過程了。
<where></where> 裏面的邏輯條件至少有一個成立,纔會出現後面的 where column = “value”,否則等於select * from student;沒有後面的where子句
<set></set>也是如此,如果都爲空,也是會報錯的,那是的sql語句大致是這樣
udpate student where column = “value”,所以他們只是簡化了非空的邏輯判斷的sql語句組合寫法,比如不用考慮是不是多個",",還有update字段的時候,是不是多個“AND”,這些mybtis都做好了,直接用就可以了

更多的戳這裏

測試類

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MybitsdemoApplication.class)
public class StudentMapperTest {
    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void insertTest() {
        //添加數據
        StudentEntity studentEntity = new StudentEntity(1, "yu", 24, "male");
        StudentEntity studentEntity1 = new StudentEntity(2, "xue", 25, "female");
        studentMapper.insert(studentEntity);
        studentMapper.insert(studentEntity1);
        Assert.assertEquals(2, studentMapper.getAll().size());
        //獲取全部數據
        List<StudentEntity> studentEntityList = studentMapper.getAll();
        for (StudentEntity studentEntitytemp : studentEntityList) {
            System.out.println(studentEntitytemp.toString());
        }

        //根據id獲取數據
        StudentEntity studentEntity2 = studentMapper.getOne(2);
        System.out.println(studentEntity2.toString());
        Assert.assertEquals("xue", studentEntity2.getName());

        //update部分數據項
        StudentEntity studentEntity3 = new StudentEntity(2, "xueshanshan", null, null);
        studentMapper.update(studentEntity3);
        //根據實體類獲取一條數據
        StudentEntity studentEntity4 = studentMapper.getOne2(studentEntity3);
        System.out.println(studentEntity4.toString());
        Assert.assertEquals("xueshanshan", studentEntity4.getName());
        //刪除數據
        studentMapper.deleteOne(2);
        Assert.assertEquals(1, studentMapper.getAll().size());


    }
}

xml更多的還是適用於複雜的sql語句,各種嵌套查詢等,這些返回結果集中也都有相對應的處理,註解形式的,相較於xml而言,就簡單多了,等我有空了再寫那個。

如果配置過程中有什麼問題,下面留言即可,我看到了會回覆的。

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