spring Boot注解SQL

更多详细用法,可以参考mybatis中文网的专门介绍

http://www.mybatis.org/mybatis-3/zh/statement-builders.html

1、在我们写的动态sql前面添加@Seclect

@Select("select * from d_technician")
	@Results(id = "techniciansMap",
	value = {
			@Result(id = true, property = "id", column = "id"),
			@Result(property = "userId",	 column = "user_id"),
			@Result(property = "skilful",	 column = "skilful"),
			@Result(property = "company", 	column = "company"),
			@Result(property = "workYear", 	column = "work_year"),
			@Result(property = "resume", 	column = "resume"),
			@Result(property = "star", 		column = "star"),
			@Result(property = "deal", 	column = "deal"),
			@Result(property = "likeNum", 	column = "like_num"),
	})
	List	getTechnicians();

条件查询,对条件进行非空判断,在sql语句中拼接

@Select("")    
public List findUserById(User user); 

2.可以在接口中 创建内部类实现,当然也可以新建一个类

class TechnicianMapperProvider{
	//结构化sql
		public	String	selectTechnicianByPara(Technician technician) {
			return new SQL() {
				{
					SELECT("*");
					FROM("d_technician");
					if (technician.getSkilful() != null) {
						WHERE("skilful = #{skilful}");
					}
					if (technician.getWorkYear() != null) {
						WHERE("work_year = #{workYear}");
					}
					if (technician.getStar() != null) {
						WHERE("star = #{star}");
					}
				}
			}.toString();
		}
	}


//增改删对应@InsertProvider、@UpdateProvider、@DeleteProvider
 
@SelectProvider(type = TechnicianMapperProvider.class,method = "selectTechnicianByPara")
	List	getTechnicians();

//结构化sql 看着高大上,但是多表查询 貌似不行,ON 字段没有(如果有遇到,用上面可以实现的,欢迎评论 )
public	String	selectTechnicianByPara(Technician technician) {
		String sql = "select * from d_technician";
        if (technician.getSkilful() != null) {
						sql+="where skiful = #{skiful}";
					}
				
            return sql;
		}


//如果觉得麻烦,可以直接编写xml脚本,可能更方便些



关于Mapper接口的注解  

注意:使用注解版需要在类上加上@Mapper注解,让SpringBoot自动扫描能识别

@Mapper  

public interface UserMapper {  

一次行扫描所有mapper 在程序启动入口加入注解:


@MapperScan(basePackages= {"com.lqy.springboot.mapper"})  
@SpringBootApplication  
public class SpringbootApplication {  

对于上面Mapper结果的映射

注意:@Results 在@Select前后都没有关系

声明时给id赋值为techniciansMap

在其他 方法中,重复使用id为techniciansMap的结果映射

@ResultMap("techniciansMap")

如果是通过xml文件来配置的话,只需要开启驼峰命名转换

mybatis:
  configuration:
    map-underscore-to-camel-case: true


 

你可能感兴趣的:(Spring,Boot,spring,boot,动态sql)