Java-MyBatis注解动态开发

首先

@Mapper
public interface DynamicSelectDao {

    @SelectProvider(type = DynamicSelectSql.class, method = "dynamicSelectSql")
    String dynamicSelect(@Param("a")String a, @Param("b")String b);

}

接着

public class DynamicSelectSql {

    private static String selectSql = "";

    public String dynamicSelectSql() {
        return selectSql.toString();
    }

    public static String getSelectSql() {
        return selectSql;
    }

    public static void setSelectSql(String selectSql) {
        DynamicSelectSql .selectSql = selectSql;
    }
}

然后

public class AnnotationMethod {

    /**
     *
     * @param a
     * @param b
     * @return value
     */
    public static String dynamicSelect(String a, String b){
        SqlSessionFactory sqlSessionFactory = SpringContextHolder.getBean(SqlSessionFactory.class);
        SqlSession session = sqlSessionFactory.openSession();
        DynamicSelectDao dynamicSelectDao = session.getMapper(DynamicSelectDao.class);
        String value = dynamicSelectDao.dynamicSelect(a,b);
        session.close();
        return value;
    }

}

最后

String executeSql ="SELECT * from data_sheet where a=#{a} and b=#{b}";
DynamicSelectSql.setSelectSql(executeSql);
/*执行SQL语句*/
String executeValue = null;
try {
    executeValue = AnnotationMethod.dynamicSelect(a,b);
} catch (Exception e) {
    e.printStackTrace();
}

 

你可能感兴趣的:(java,mybatis)