Mybatis的@select和@SelectProvider注解方式动态SQL语句解读
作者:DegenerateAng
这篇文章主要介绍了Mybatis的@select和@SelectProvider注解方式动态SQL语句,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
Mybatis中提供一种非常简便的开发方式,通过注解的方式写SQL语句,它还可以实现多种写法,
下面就了解一下如何通过注解方式实现动态SQL的整个过程:
配置xml文件:Spring+Mybatis
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 封装数据源,连接数据库属性 --> <bean id="dataSouce" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="net.sf.log4jdbc.DriverSpy"></property> <property name="url" value="jdbc:mysql://localhost:3306/mybas"></property> <property name="username" value="root"></property> <property name="password" value="scott"></property> </bean> <!-- 创建SqlSessionFactory对象 --> <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库连接信息来源于 dataSource --> <property name="dataSource" ref="dataSouce"></property> </bean> <!-- 扫描器相当于mybatis.xml中 mappers下package标签,扫描com.bjsxt.mapper包后会给对应接口创建对象 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 要扫描哪个包 --> <property name="basePackage" value="com.gx.service"></property> <!-- 和factory产生关系 --> <property name="sqlSessionFactory" ref="factory"></property> </bean> <!-- 由spring管理service实现类 account实现类中的set方法 --> <bean id="accounts" class="com.gx.serviecImpl.accountserviceImpl"> <property name="account" ref="accountservice"></property> </bean> </beans>
创建实体类
package com.gx.pojo; public class account { private int accountID; private String num; private String password; private Double balance; private String name; public int getAccountID() { return accountID; } public void setAccountID(int accountID) { this.accountID = accountID; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Double getBalance() { return balance; } public void setBalance(Double balance) { this.balance = balance; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "account [accountID=" + accountID + ", num=" + num + ", password=" + password + ", balance=" + balance + ", name=" + name + "]"; } }
接口文件类(注解写法)
里面包含有增删改查,注意@的注解,有所不同;
@Param("")给参数取别名;
package com.gx.service; import java.util.List; import mapper.SqlContext; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.SelectProvider; import org.apache.ibatis.annotations.Update; import com.gx.pojo.account; public interface accountservice { @SelectProvider(method = "selectaccount", type = SqlContext.class) List<account> show(account account); @Select("select * from account ") List<account> showTwo(); @Select("select * from account where num=${number }") List<account> showThree(@Param("number") String number); @Select("select * from account where name='${accounts.name}'") List<account> showFour(@Param("accounts")account accounts); @Select("SELECT account.*,accounttow.number FROM account JOIN accounttow ON accounttow.accountID=account.num ") List<account> showFive(); @Insert("INSERT account(num,password,balance,name) VALUES('${ac.num}','${ac.password}',${ac.balance},'${ac.name}');") boolean insertAccount(@Param("ac")account account); @Delete("DELETE FROM account WHERE name='${ac.name}'") boolean delectAccount(@Param("ac")account account); @Update("UPDATE account SET balance=${ac.balance} WHERE NAME='${ac.name}'") boolean updataAccount(@Param("ac")account account); }
@SelectProvider(method = "selectaccount", type = SqlContext.class)
@SelectProvider一般用于多条件查询使用,多表查询可以直接使用@Select去·写如showFive;
多条件查询可以在类文件中写,Mybatis支持在类文件中写动态SQL;
一个类可以有多个SQL,type 是类文件名称,method是方法指定里面的SQL;
SQL类的写法
package mapper; import org.apache.ibatis.jdbc.SQL; import com.gx.pojo.account; public class SqlContext { public String selectaccount(final account account){ return new SQL(){ { SELECT("*"); FROM("account"); if(account.getNum()!=null && account.getNum()!="0"){ WHERE(" num=#{num } "); } if (account.getName()!=null && account.getName()!="") { WHERE(" name=#{name } "); }} }.toString(); } }
serviceImpl(实现接口)
package com.gx.serviecImpl; import java.util.List; import com.gx.pojo.account; import com.gx.service.accountservice; public class accountserviceImpl implements accountservice{ private accountservice ac; public accountservice getAccount(){ return ac; } //依赖注入时必须的setter方法 public void setAccount(accountservice accountservices){ this.ac=accountservices; } @Override public List<account> show(account account) { // TODO Auto-generated method stub return ac.show(account); } @Override public List<account> showTwo() { // TODO Auto-generated method stub return ac.showTwo(); } @Override public List<account> showThree(String num) { // TODO Auto-generated method stub return ac.showThree(num); } @Override public List<account> showFour(account accounts) { // TODO Auto-generated method stub return ac.showFour(accounts); } @Override public boolean insertAccount(account account) { // TODO Auto-generated method stub return ac.insertAccount(account); } @Override public boolean delectAccount(account account) { // TODO Auto-generated method stub return ac.delectAccount(account); } @Override public boolean updataAccount(account account) { // TODO Auto-generated method stub return ac.updataAccount(account); } @Override public List<account> showFive() { // TODO Auto-generated method stub return ac.showFive(); } }
Servlet:使用(Spring+Mybatis)
创建工厂和实例化方法,并且调用方法;
package com.gx.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.gx.pojo.account; import com.gx.serviecImpl.accountserviceImpl; public class accountServlet extends HttpServlet { //私有化serviceImpl实现类 private accountserviceImpl accountservice; @Override public void init() throws ServletException { WebApplicationContext ac = WebApplicationContextUtils .getRequiredWebApplicationContext(getServletContext()); accountservice = ac.getBean("accounts", accountserviceImpl.class); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("UTF-8"); account account=new account(); account.setNum("4"); account.setBalance(1000.0); account.setName("吴六"); account.setPassword("4"); System.out.println("我是show方法"+accountservice.show(account)); System.out.println("我是showTwo方法"+accountservice.showTwo()); System.out.println("我是showThree方法"+accountservice.showThree("2")); System.out.println("我是showFour方法"+accountservice.showFour(account)); System.out.println("我是insertAccount方法"+accountservice.insertAccount(account)); System.out.println("我是updataAccount方法"+accountservice.updataAccount(account)); System.out.println("我是delectAccount方法"+accountservice.delectAccount(account)); req.setAttribute("list", accountservice.show(account)); req.getRequestDispatcher("/index.jsp").forward(req, resp); } /** * */ private static final long serialVersionUID = 1L; }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。