Mybatis 执行传入的sql语句

在项目开发中,需要根据具体业务逻辑动态拼接sql语句,那么我们可以将动态拼接好的sql语句传入mybatis中,这样便能最大限度将sql掌握在自己手里。

1.构造实体类(此处省略get、set方法)

package com.dnf.entity;

public class Staff {
    private long id;
    private String userName;
    private String password;
}

2.构造接口类

package com.dnf.dao;

import java.util.List;

import com.dnf.entity.Staff;

/** * @author Marco * */
public interface StaffDao {

    List<Staff> query4staff(String sql);
}

3.配置mapper文件

<?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.dnf.dao.StaffDao">
    <!-- 目的:为dao接口方法提供sql语句配置 -->
    <select id="query4staff" parameterType="String" resultType="Staff">
        ${value}
    </select>
</mapper>

以上三步配置好了对应的文件,下面进行测试

1.建立Base测试类将spring和junit整合

package com.dnf;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/** * 配置spring和junit整合,junit启动时加载springIOC容器 spring-test,junit */
@RunWith(SpringJUnit4ClassRunner.class)
// 告诉junit spring配置文件
@ContextConfiguration({ "classpath:spring/spring-dao.xml", "classpath:spring/spring-service.xml" })
public class BaseTest {

}

2.创建StaffTest的测试类

package com.dnf.dao;

import java.util.List;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.dnf.BaseTest;
import com.dnf.entity.Staff;

public class StaffTest extends BaseTest{

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private StaffDao dao;   

    @Test
    public void query4staff(){
        String sql = "SELECT id,user_name,password FROM staffs";
        List<Staff> list = dao.query4staff(sql);
        for(Staff staff : list){
            logger.info(staff.toString());
        }
    }

}

执行junit测试
《Mybatis 执行传入的sql语句》

至此,配置完成。

    原文作者:SQL
    原文地址: https://blog.csdn.net/Laichilueng/article/details/76842205
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞