SSM整合


第一步:准備依賴

1、Spring-core beans expression context aop tx jdbc web webmvc
2、Druid MySQL-connector-java mybatis mybatis-spring
3、 Log4j slf4j-api slf4j-log4j12
4、Jstl servlet-api Lombok aspectjweaver

第二步:項目准備

1、數據庫准備,准備好測試要用的表及數據

2、架構設計

 3、bean中的類(屬性與數據庫中的表對應)

@Setter@Getter@AllArgsConstructor@NoArgsConstructor@ToString
public class User {
    private Integer id;
    private String username;
    private String pwd;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date date;
    public String getDate(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(this.date);
    }
}
User

  條件查詢時封裝的條件類

@Setter@Getter@ToString
public class QueryBean {

    private String username;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private String date;
    private Integer currentPage;
    private Integer pageSize;
    //修改set方法可以在接收前端參數進行封裝時進行判斷修改
    public void setCurrentPage(Integer currentPage){
        if(currentPage!=null){
            this.currentPage=currentPage;
        }else{
            this.currentPage=1;
        }
    }
    public void setPageSize(Integer pageSize){
        if(pageSize!=null){
            this.pageSize=pageSize;
        }else{
            this.pageSize=3;
        }
    }

    //重寫get方法,對多條件的結果進行預判斷,可以減少xml中配置的代碼
    public String getUsername(){
        return StringUtils.isNullOrEmpty(this.username)?null:this.username;
    }
    public String getDate(){
        return StringUtils.isNullOrEmpty(this.date)?null:this.date;
    }
    //使用getStart方法可以返回start屬性,在定義分頁工具查詢時使用
    public Integer getStart(){
        return (this.currentPage-1)*this.pageSize;
    }

    /*如果使用date類型的date,可以將get方法返回的結果轉換格式返回
    public String getDate(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(this.date);
    }*/
}
條件查詢時封裝的條件類QueryBean

4、mapper接口,以及對應方法的xml文件

public interface UserMapper {
    //增刪改查
    Integer save(User user);
    Integer update(User user);
    Integer delete(Integer id);
    User findById(Integer id);
    List<User> findAll();
    //條件查詢用到的方法
    List<User> select(QueryBean queryBean);

    //登錄檢查需要用到的方法
    String login(String username);
    //手動實現分頁需要用到的方法
    Integer selectCount(QueryBean queryBean);
    List<User> selectAll(QueryBean queryBean);
}
UserMapper接口
<?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.test.ssm.mapper.UserMapper">
    <insert id="save">
        insert into users values(null,#{username},#{pwd},#{date})
    </insert>
    <update id="update">
        update users set username=#{username},pwd=#{pwd},date=#{date} where id=#{id}
    </update>
    <delete id="delete">
        delete from users where id=#{id}
    </delete>

    <resultMap id="myResultMap" type="user">
        <id property="id" column="id"/>
        <result column="username" property="username"/>
        <result column="pwd" property="pwd"/>
        <result column="date" property="date"/>
    </resultMap>

    <select id="findById" resultMap="myResultMap">
        select * from users where id=#{id}
    </select>

    <select id="findAll" resultMap="myResultMap">
        select * from users
    </select>

    <select id="select" resultMap="myResultMap">
        select * from users
        <where>
            <!--在條件類中將get方法封裝后可以簡化的代碼
            <if test="username!=null and username!=''">
                and username like concat('%',#{username},'%')
            </if>
            <if test="date!=null and date!=''">
                and date like concat('%',#{date},'%')
            </if>-->
            <if test="username!=null">
                and username like concat('%',#{username},'%')
            </if>
            <if test="date!=null">
                and date like concat('%',#{date},'%')
            </if>
        </where>
    </select>
    
    <!--手動實現分頁需要用到的查詢,查詢總條數-->
    <select id="selectCount" resultType="integer">
        select count(*) from users
        <where>
            <if test="username!=null">
                and username like concat('%',#{username},'%')
            </if>
            <if test="date!=null">
                and date like concat('%',#{date},'%')
            </if>
        </where>
    </select>
    <!--手動實現分頁需要用到的查詢,條件查詢-->
    <select id="selectAll" resultMap="myResultMap">
        select * from users
        <where>
            <if test="username!=null">
                and username like concat('%',#{username},'%')
            </if>
            <if test="date!=null">
                and date like concat('%',#{date},'%')
            </if>
        </where>
        limit #{start},#{pageSize}
    </select>

    <!--登錄檢測需要用到的查詢-->
    <select id="login" resultType="java.lang.String">
        select pwd from users where username=#{username}
    </select>
</mapper>
UserMapper.xml

5、service接口,以及實現類(使用mapper對象)

  傳統的方式是

  1:獲取Factory對象,new SqlSessionFactoryBuilder().build(輸入流);

  2:獲取SqlSession對象,Factory.openSession()

  3:獲取mapper對象,SqlSession.getMapper()

  整合后的方式為

  1.配置MapperFactoryBean(一次只能創建一個) mapperScannerConfigurer(批量創建,從配置的包中掃描所有賽接口,並且創建代理對象)

  2.兩個屬性,一個是要創建的接口<property name="mapperInterface" value=""/>,一個是sqlsessionfactory

  3.配置sqlsessionfactory,幾個主要屬性

    數據源dataSource
    配置別名typeAliasesPackage
    關聯mapper映射文件mapperLocations
    關聯mybatis的主配置文件configLocation

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
">
    <!--加載數據庫的配置文件-->
    <context:property-placeholder location="classpath:db.properties" system-properties-mode="NEVER"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--數據源-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置別名-->
        <property name="typeAliasesPackage" value="com.test.ssm.bean"/>
        <!--關聯mapper映射文件-->
        <property name="mapperLocations" value="classpath:com/test/ssm/mapper/*Mapper.xml"/>
        <!--關聯mybatis的主配置文件-->
        <property name="configLocation" value="classpath:mybatis.xml"/>
    </bean>

    <!--<bean id="mapperFactory" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.test.ssm.mapper.UserMapper"/>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

    <bean id="service" class="com.test.ssm.service.impl.UserServiceImpl">
        <property name="userMapper" ref="mapperFactory"/>
    </bean>-->

    <!--配置mapper接口掃描器MapperScannerConfigurer
        會從配置的包中,掃描所有的接口,並且創建接口的代理對象
        下面的bean等同與上面注釋的兩個的作用
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.test.ssm.mapper"/>
        <!--當配置文件中只有一個數據源的時候,可以不寫這個參數
        有多個數據源的時候,需要指定使用哪個數據源-->
        <!--<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />-->
    </bean>

    <!--IoC注解掃描-->
    <context:component-scan base-package="com.test.ssm"/>
    <!--事務管理器-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

    <!--使用注解方式只需要配置事務注解驅動,然后將事務管理器進行綁定
    在需要事務控制的類上貼上@Transactional即可-->
    <!--<aop:config>
        <aop:pointcut id="pointcut" expression="execution( * com.test.ssm.service..*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>-->

    <!--事務管理器注解驅動-->
    <tx:annotation-driven transaction-manager="txManager"/>
</beans>
applicationContext.xml
public interface UserMapper {
    //增刪改查
    Integer save(User user);
    Integer update(User user);
    Integer delete(Integer id);
    User findById(Integer id);
    List<User> findAll();
    //條件查詢用到的方法
    List<User> select(QueryBean queryBean);

    //登錄檢查需要用到的方法
    String login(String username);
    //手動實現分頁需要用到的方法
    Integer selectCount(QueryBean queryBean);
    List<User> selectAll(QueryBean queryBean);
}
IUserService
@Service
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    public Integer save(User user) {
        return userMapper.save(user);
    }

    public Integer update(User user) {
        Integer update = userMapper.update(user);
        //System.out.println(1/0);
        return update;
    }

    public Integer delete(Integer id) {
        return userMapper.delete(id);
    }

    public User findById(Integer id) {
        return userMapper.findById(id);
    }

    public List<User> findAll() {
        return userMapper.findAll();
    }

    public Boolean login(String username, String pwd) {
        String login = userMapper.login(username);
        if(login.equals(pwd)){
            return true;
        }
        return false;
    }

    public List<User> select(QueryBean queryBean) {

        return userMapper.select(queryBean);
    }

    //分頁插件的使用
    public PageInfo<User> select2(QueryBean queryBean) {
        PageHelper.startPage(queryBean.getCurrentPage(),queryBean.getPageSize());
        List<User> list = userMapper.select(queryBean);
        PageInfo<User> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /*將屬性封裝到類中,減少業務端代碼
    public PageUtils select3(QueryBean queryBean) {
        Integer total = userMapper.selectCount(queryBean);
        PageUtils pageUtils = new PageUtils();
        //從前台取出的數據賦值
        pageUtils.setPageNum(queryBean.getCurrentPage());
        pageUtils.setPageSize(queryBean.getPageSize());
        //從數據庫中查詢出的數據賦值
        pageUtils.setList(userMapper.selectAll(queryBean));
        pageUtils.setTotal(total);
        //經過計算得到的數據賦值
        int pages = Double.valueOf(Math.ceil(pageUtils.getTotal()*1.0/pageUtils.getPageSize())).intValue();
        pageUtils.setPages(pages);
        Integer nextPage;
        if(queryBean.getCurrentPage()==pageUtils.getPages()){
            nextPage=1;
        }else{
            nextPage=queryBean.getCurrentPage()+1;
        }
        pageUtils.setNextPage(nextPage);
        Integer prePage;
        if(queryBean.getCurrentPage()==1){
            prePage=pageUtils.getPages();
        }else{
            prePage=queryBean.getCurrentPage()-1;
        }
        pageUtils.setPrePage(prePage);

        return pageUtils;
    }*/
    public PageUtils select3(QueryBean queryBean) {
        Integer total = userMapper.selectCount(queryBean);
        if(total==0){
            //可以減少一次查詢,提高效率
            return new PageUtils(queryBean.getCurrentPage(),queryBean.getPageSize(),null,total);
        }
        List<User> list = userMapper.selectAll(queryBean);
        return new PageUtils(queryBean.getCurrentPage(),queryBean.getPageSize(),list,total);
    }

}
UserServiceImpl

6、這時可先測試一下代碼,使用測試類App測試增刪改查

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class App {
    @Autowired
    private IUserService userService;

    @Test
    public void testSave(){
        User user = new User(null,"林丹","qwer",new Date());
        userService.save(user);
    }
    @Test
    public void testUpdate(){
        User user =new User(10,"小芳","qwer",new Date());
        userService.update(user);
    }
    @Test
    public void testDelete(){
        userService.delete(5);
    }
    @Test
    public void testFindOneById(){
        System.out.println(userService.findById(3));
    }
    @Test
    public void testFindAll(){
        System.out.println(userService.findAll());
    }

}
App

 第三步:添加事務控制

1、添加依賴 aspectj

2、配置事務管理器,本質上是一個<bean id="txManager" class=""/>

3、配置事務(兩種方式)

   1.xml方式

    <aop:config>
        <aop:pointcut id="pointcut" expression="execution( * com.test.ssm.service..*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

  2.使用注解的方式

  配置事務管理器,需要配置事務管理器注解驅動@Transactional即可

<!--事務管理器注解驅動-->
    <tx:annotation-driven transaction-manager="txManager"/>

第四步:配置前端頁面

1、導入依賴servlet-api

2、在web.xml中配置前端控制器(本質上是一個servlet)

  客戶端訪問時會先通過前端控制器,再通過攔截器

<!--配置前端控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--配置有請求訪問時加載的文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springMVC.xml</param-value>
    </init-param>
    <!--配置自動啟動前端控制器-->
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  注意:配置中的文件關聯有沒有將配置信息引入,可以在springMVC中使用import標簽進行引入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--引入后台的Spring配置文件-->
    <import resource="classpath:applicationContext.xml"/>

</beans>

3、在web.xml中配置編碼過濾器,解決中文亂碼問題

<!--請求編碼過濾器-->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!--設置編碼格式-->
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <!--設置請求和響應是否強制編碼-->
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

4、在springMVC中配置攔截器,攔截想要跳過登錄界面訪問受保護資源的請求

<!--攔截器-->
   <mvc:interceptors>
       <!--登錄檢查攔截器-->
       <!--路徑/**表示攔截所有路徑,/*只能攔截所有一級路徑-->
       <mvc:interceptor>
           <mvc:mapping path="/**"/>
           <!--對某個請求放行-->
           <mvc:exclude-mapping path="/login.do"/>
           <!--配置攔截器的全限定名-->
           <bean class="com.test.ssm.interceptor.MyInterceptor"></bean>
       </mvc:interceptor>
   </mvc:interceptors>

  攔截器

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if(session.getAttribute("USER_IN_SESSION")==null){
            response.sendRedirect("/index.html");
            return false;
        }
        return true;
    }
}
MyInterceptor

 第五步:編寫Controller和訪問頁面

  在web.xml中添加如下代碼,可以默認訪問此頁面

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

   Controller代碼示例

@Controller
public class UserController {

    @Autowired
    private IUserService userService;
    
    @RequestMapping("/findAll")
    public String findAll(Model model){
        List<User> list = userService.findAll();
        model.addAttribute("list",list);
        return "list";
    }
    @RequestMapping("/login")
    public String login(String username, String pwd, HttpSession session){
        Boolean login = userService.login(username, pwd);
        if(login){
            session.setAttribute("USER_IN_SESSION",username);
            return "redirect:/findAll.do";
        }
        return "redirect:/index.html";
    }
    @RequestMapping("/edit")
    public String edit(Integer id,Model model){
        if(id!=null){
            model.addAttribute("user",userService.findById(id));
        }
        return "edit";
    }
    //將添加和保存寫在同一個頁面內
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(User user){
        if(user.getId()!=null){
            userService.update(user);
        }else{
            userService.save(user);
        }
        return "redirect:/findAll.do";
    }
    @RequestMapping("/delete")
    public String delete(Integer id){
        if(id!=null){
            userService.delete(id);
        }
        return "redirect:/findAll.do";
    }
    
    //條件查詢
    @RequestMapping("/select")
    public String select(@ModelAttribute("queryBean") QueryBean queryBean, Model model){
        List<User> list = userService.select(queryBean);
        model.addAttribute("list",list);
        return "list";
    }

    //使用分頁插件進行條件查詢
    @RequestMapping("/select2")
    public String select2(@ModelAttribute("queryBean") QueryBean queryBean, Model model){
        PageInfo<User> pageInfo = userService.select2(queryBean);
        model.addAttribute("page",pageInfo);
        return "list";
    }

    //使用自己定義的分頁功能進行條件查詢
    @RequestMapping("/select3")
    public String select3(@ModelAttribute("queryBean") QueryBean queryBean, Model model){
        PageUtils pageUtils = userService.select3(queryBean);
        model.addAttribute("page",pageUtils);
        return "list";
    }
}
UserController

   頁面代碼

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>Hello World!</h2>
<form action="/login.do" method="post">
    用戶名:<input type="text" name="username"/>
    密碼:<input type="text" name="pwd"/>
    <input type="submit"/>
</form>
</body>
</html>
index.html

  下面兩個頁面在WEB-INF下的views里,是受保護頁面,list中現在還沒有分頁功能,將page.list替換為list即可,分頁功能在下篇博客中詳細說明。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<div style="text-align: center;">
    <h2>用戶編輯</h2>
    <form action="/saveOrUpdate.do" method="post">
        <input type="hidden" name="id" value="${user.id}"/>
        用戶名:<input type="text" name="username" value="${user.username}"/>
  <br/>密碼:<input type="text" name="pwd" value="${user.pwd}"/><br/>
        日期:<input type="date" name="date" value="${user.date}"/><br/>
        <input type="submit" value="保存"/>
    </form>
</div>
</body>
</html>
edit.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript">
        function goPage(page) {
            //設置當前頁的值
            document.getElementById("currentPage").value = page;
            //提交表單
            var form = document.getElementById("f1");
            form.submit();   //提交表單
        }
    </script>
</head>
<body>
<div style="text-align: center;">
<h1>用戶列表</h1>

    <%--使用了對象進行參數接受的時候,在參數封裝的同時會將對象加入到作用域中 --%>
    <form id="f1" action="/select3.do" method="post">

        用戶姓名:<input type="text" name="username" value="${queryBean.username}"/>
        注冊日期:<input type="text" name="date" value="${queryBean.date}"/>
        <input type="submit" value="查詢"/>
        <input type="button" onclick="location.href='/edit.do'" value="增加" style="width: 40px;text-align: center"/>
    <table border="1px" width="60%" style="text-align: center;margin: 0 auto;">
        <tr>
            <th>編號</th>
            <th>姓名</th>
            <th>密碼</th>
            <th>注冊日期</th>
            <th>操作</th>
        </tr>
        <c:forEach items="${page.list}" var="user" varStatus="index">
            <tr>
                <td>${index.count}</td>
                <td>${user.username}</td>
                <td>${user.pwd}</td>
                <td>${user.date}</td>
                <td><a href="/edit.do?id=${user.id}">修改</a>|<a href="/delete.do?id=${user.id}">刪除</a></td>
            </tr>
        </c:forEach>

        <tr>
            <td colspan="5">
                <a href="javascript:void(0);" onclick="goPage(1)">首頁</a>
                <a href="javascript:void(0);" onclick="goPage(${page.prePage})">上一頁</a>
                <a href="javascript:void(0);" onclick="goPage(${page.nextPage})">下一頁</a>
                <a href="javascript:void(0);" onclick="goPage(${page.pages})">尾頁</a>
                <input type="text" name="currentPage" id="currentPage"/>
                <input type="submit" value="跳轉"/>
                每頁顯示:
                <select name="pageSize" onchange="goPage(1)">
                    <option value="3" ${queryBean.pageSize==3?'selected':''}>3</option>
                    <option value="4" ${queryBean.pageSize==4?'selected':''}>4</option>
                    <option value="5" ${queryBean.pageSize==5?'selected':''}>5</option>
                </select>
                當前${page.pageNum}頁/共${page.pages}頁/共${page.total}條記錄
            </td>
        </tr>
    </table>
    </form>
</div>
</body>
</html>
list.jsp

第六步:加入多條件查詢

可以將條件封裝到一個類中的屬性上

@Setter@Getter@ToString
public class QueryBean {

    private String username;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private String date;
    private Integer currentPage;
    private Integer pageSize;
    //修改set方法可以在接收前端參數進行封裝時進行判斷修改
    public void setCurrentPage(Integer currentPage){
        if(currentPage!=null){
            this.currentPage=currentPage;
        }else{
            this.currentPage=1;
        }
    }
    public void setPageSize(Integer pageSize){
        if(pageSize!=null){
            this.pageSize=pageSize;
        }else{
            this.pageSize=3;
        }
    }

    //重寫get方法,對多條件的結果進行預判斷,可以減少xml中配置的代碼
    public String getUsername(){
        return StringUtils.isNullOrEmpty(this.username)?null:this.username;
    }
    public String getDate(){
        return StringUtils.isNullOrEmpty(this.date)?null:this.date;
    }
    //使用getStart方法可以返回start屬性,在定義分頁工具查詢時使用
    public Integer getStart(){
        return (this.currentPage-1)*this.pageSize;
    }

    /*如果使用date類型的date,可以將get方法返回的結果轉換格式返回
    public String getDate(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(this.date);
    }*/
}
條件查詢時封裝的條件類QueryBean

sql查詢語句select * from users where name like concat('%',#{},'%'),concat的作用是合並字符串

    <select id="select" resultMap="myResultMap">
        select * from users
        <where>
            <!--在條件類中將get方法封裝后可以簡化的代碼
            <if test="username!=null and username!=''">
                and username like concat('%',#{username},'%')
            </if>
            <if test="date!=null and date!=''">
                and date like concat('%',#{date},'%')
            </if>-->
            <if test="username!=null">
                and username like concat('%',#{username},'%')
            </if>
            <if test="date!=null">
                and date like concat('%',#{date},'%')
            </if>
        </where>
    </select>
多條件查詢xml中的配置

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM