动态SQL注解
脚本SQL
- 在
<script></script>
标签中间按照之前sqlmap中的动态sql的样式书写
@Select("<script>select * from student "
+ "<where>"
+ "<if test =\"ssex != null\"> and ssex=#{ssex} </if>"
+ "<if test =\"classid != 0\"> and classid=#{classid} </if>"
+ "</where>"
+ "</script>")
public List<Student> selectStudent(Student s);
方法中构建sql
在接口中定义内部类,来构建需要的动态sql语句,比使用标签的方式结构更加清晰
@UpdateProvider(type = StudentSql.class,method ="xiugaiStuSql")
public int updateStudentFun(Student s);
// 内部类
class StudentSql{
public String xiugaiStuSql(Student s ) {
String sql = "update student set";
int count = 0;
if(s.getSname() !=null) {
sql+=",sname =#{sname}";
}
if(s.getBirthday() !=null) {
sql+=",birthday = #{birthday}";
}
if(s.getSsex()!=null) {
sql+=",ssex =#{ssex}";
}
if(s.getClassid()!=0) {
sql+=",classid =#{classid}";
}
sql+=" where sid =#{sid}";
sql = sql.replaceFirst(",", " ");
return sql;
}
}
-
@UpdateProvider:
-
创建sql语句类
该类包含需要动态生成的SQL 语句
-
创建Mapper接口类
该类和配置文件的接口文件一样,用来处理数据库操作
-
利用@UpdateProvider
将 SQL 语句类和 Mapper 接口类关联,利用@UpdateProvider的 type 属性和 method 属性
- type:内部类名称
- method :方法名称
-
测试验证
编写测试类,测试动态生成的SQL 语句是否准确
-
-
内部类:内部类最终要返回一个sql语句,即字符串类型
-
新增:@InsertProvider、修改:@UpdateProvider
删除:@DeleteProvider、查询:@SelectProvider
SQL语句构造器
-
功能:
解决 Java 代码中嵌入 SQL 语句,通过简单地创建一个实例来调用方法生成SQL语句
-
特点:
没有过多的使用类如 and的连接词
@SelectProvider(type = StudentSql.class,method = "selectByGZQ")
public List<Student> selectStuByGZQ(Student s);
@InsertProvider(type = StudentSql.class,method = "insertByGZQ")
@Options(keyProperty = "sid",useGeneratedKeys = true)
public int insertStuByGZQ(Student s);
@UpdateProvider(type = StudentSql.class,method = "updateByGZQ")
public int updateStuByGZQ(Student s);
@DeleteProvider(type = StudentSql.class,method = "deleteByGZQ")
public int deleteStuByGZQ(int sid);
// 内部类
class StudentSql{
// sql构造器
public String selectByGZQ(Student s) {
return new SQL() {
{
SELECT("*");
FROM("student");
if(s.getSsex()!=null) {
WHERE("ssex = #{ssex}");
}
if(s.getClassid()!=0) {
WHERE("classid = #{classid}");
}
}
}.toString();
}
public String insertByGZQ(Student s) {
return new SQL() {
{
INSERT_INTO("student");
if(s.getSname()!=null) {
VALUES("sname", "#{sname}");
}
if(s.getBirthday()!=null) {
VALUES("birthday","#{birthday}");
}
if(s.getSsex()!=null) {
VALUES("ssex","#{ssex}");
}
if(s.getClassid()!=0) {
VALUES("classid","#{classid}");
}
}
}.toString();
}
public String updateByGZQ(Student s) {
return new SQL() {
{
UPDATE("student");
if(s.getSname()!=null) {
SET("sname=#{sname}");
}
if(s.getBirthday()!=null) {
SET("birthday=#{birthday}");
}
if(s.getSsex()!=null) {
SET("ssex=#{ssex}");
}
if(s.getClassid()!=0) {
SET("classid=#{classid}");
}
WHERE("sid = #{sid}");
}
}.toString();
}
public String deleteByGZQ(int sid) {
return new SQL() {
{
DELETE_FROM("student");
WHERE("sid = #{sid}");
}
}.toString();
}
}
注意事项: