1. 程式人生 > >mybatis註解實現 spring mvc + mybatis+velocity 框架 (附完整專案程式碼)

mybatis註解實現 spring mvc + mybatis+velocity 框架 (附完整專案程式碼)

最近學習了一下mybatis結合網上的一些列子搭建的一個網站的框架,前端顯示用的velocity引擎,資料訪問使用mybatis+oracle,檢視訪問控制spring mvc,框架主要包括一些基本的增刪改操作以及攔截器,廢話不多說了直接開始吧!! 程式碼下載地址最下面

整體專案預覽

專案執行效果圖
查詢結果
登陸
1.首先架包
比較懶直接用的myeclipse到入的就沒有刪除比如mysql驅動velocity工具包,還有struts一些沒用到的架包

2.實體類就是一個普通的 java bean 也沒多少欄位,本身只為了框架搭建
java bean
3.application配置

<!-- 掃描各個包 -->
    <context:component-scan base-package="com.*"
>
<!-- 不掃描帶有@Controller註解的類 --> <context:exclude-filter type="annotation" expression="com.mybatis.controller.LoginAction" /> </context:component-scan> <!-- 配置DataSource資料來源 --> <!-- 引入配置檔案 --> <context:property-placeholder
location="classpath:config.properties" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property
name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" /> </bean> <!-- 建立mybatis sqlsessionFactory工廠 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis.xml" /> <!-- mapper和resultmap配置路徑 --> <property name="mapperLocations"> <list> <!-- 表示在com.resultmap包或以下所有目錄中,以-resultmap.xml結尾所有檔案 --> <!-- <value>classpath:com/mybatis/mapper/*-mapper.xml</value> --> <value>classpath:com/mybatis/mapper/*-mapper.xml</value> <!-- 自定義 --> <!-- <value>classpath:com/mybatis/mapper/book-mapper.xml</value> --> <!-- <value>classpath:com/mybatis/mapper/student-mapper.xml</value> --> </list> </property> </bean> <!-- 通過掃描的模式,掃描目錄在com/mapper目錄下,所有的mapper都繼承SqlMapper介面的介面, 這樣一個bean就可以了 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.mybatis.mapper" /> <property name="markerInterface" value="com.mybatis.mapper.SqlMapper" /> </bean> <!-- 不定義通用的話每個類就要寫下面的配置了 --> <!-- <bean id="bookMaper" class="org.mybatis.spring.mapper.MapperFactoryBean"> --> <!-- <property name="mapperInterface" value="com.mybatis.mapper.BookMapper"></property> --> <!-- <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> --> <!-- </bean> --> <!-- velocity表示式需要的配置 --> <bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> <!--宣告模板檔案所在的路徑 (實際資原始檔所在的資料夾) --> <property name="resourceLoaderPath" value="WEB-INF/template/"></property> <!--設定輸入輸出的編碼方式 --> <property name="velocityProperties"> <props> <prop key="input.encoding">utf-8</prop> <prop key="output.encoding">utf-8</prop> </props> </property> </bean> <!-- spring 管理下velocity配置 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <property name="cache" value="true" /> <property name="prefix" value="" /> <!-- 宣告velocity表示式支援的字尾 --> <property name="suffix" value=".html"></property> <!-- 如果你需要使用Spring 對 Velocity巨集命令的支援, 將這個屬性設為true --> <property name="exposeSpringMacroHelpers" value="true" /> <property name="contentType" value="text/html;charset=utf-8" /> <!-- velocity時間格式化工具 --> <property name="dateToolAttribute" value="date"></property> <!-- 是否開放session --> <property name="exposeSessionAttributes" value="true"></property> <!-- 是否開放request --> <property name="exposeRequestAttributes" value="true"></property> <!-- request引用的名稱 --> <property name="requestContextAttribute" value="rc"></property> </bean> <!-- 啟用支援Annotation註解方式的事務管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 自定義攔截鏈配置 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/front/**" /> <!-- <mvc:mapping path="/front/bgIndex/**"/> --> <bean class="com.common.interceptor.MyInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> </beans>

mybatis 配置就相對東西少很多了

<configuration>
    <!-- 別名 -->
    <settings>
        <!-- 全域性對映器啟用快取 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 查詢時,關閉關聯物件即時載入以提高效能 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- 設定關聯物件載入的形態,此處為按需載入欄位(載入欄位由SQL指 定),不會載入關聯表的所有欄位,以提高效能 -->
        <setting name="aggressiveLazyLoading" value="false" />
        <!-- 對於未知的SQL查詢,允許返回不同的結果集以達到通用的效果 -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!-- 允許使用列標籤代替列名 -->
        <setting name="useColumnLabel" value="true" />
        <!-- 允許使用自定義的主鍵值(比如由程式生成的UUID 32位編碼作為鍵值),資料表的PK生成策略將被覆蓋 
        允許JDBC 生成主鍵。需要驅動器支援。如果設為了true,這個設定將強制使用被生成的主鍵,有一些驅動器不相容不過仍然可以執行。  default:false-->
        <setting name="useGeneratedKeys" value="false" />
        <!-- 給予被巢狀的resultMap以欄位-屬性的對映支援 -->
        <setting name="autoMappingBehavior" value="FULL" />
        <!-- 對於批量更新操作快取SQL以提高效能 -->
        <setting name="defaultExecutorType" value="BATCH" />
        <!-- 資料庫超過25000秒仍未響應則超時 -->
        <setting name="defaultStatementTimeout" value="25000" />
    </settings>


    <!-- 全域性別名設定,在對映檔案中只需寫別名,而不必寫出整個類路徑 -->
    <typeAliases>
        <typeAlias type="com.mybatis.bean.Student" alias="student" />
        <typeAlias type="com.mybatis.bean.Book" alias="book" />
    </typeAliases>

config.properties 配置

jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url = jdbc:oracle:thin:@localhost:1521:ORCL
jdbc.username =SCOTT 
jdbc.password =oracle  

Studentdao 層 注意SqlMapper只是一個空介面而已

package com.mybatis.mapper;

import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;

import com.mybatis.bean.Student;

public interface StudentMapper extends SqlMapper {



//   @SelectProvider(type = TestSqlProvider.class, method = "getSql") : 提供查詢的SQL語句,如果你不用這個註解,
//   你也可以直接使用@Select("select * from ....")註解,把查詢SQL抽取到一個類裡面,方便管理,同時複雜的SQL也容易操作,
//   type = TestSqlProvider.class就是存放SQL語句的類,而method = "getSql"表示get介面方法需要到TestSqlProvider類的getSql方法中獲取SQL語句。 

//   @ResultMap(value="com.mapper.StudentMapper.student")
//   @Select("SELECT stu.student_id,stu.student_name,stu.student_phone,stu.student_class_id FROM student stu")
//   public List<Student> getStudentList();


    /**
     * 不使用註解則需在對應的xml檔案中編寫sql語句 注意id與這裡的方法對應
     * @return
     */
     public List<Student> getAllStudent();


     public void  addStudent(Student stu);



     @ResultMap(value="com.mybatis.mapper.StudentMapper.studentMap")
     @Select("select * from student where student_Id = #{studentId}")
     public Student findStudentById(@Param("studentId") Integer studentId);

}

bookdao 層 注意SqlMapper只是一個空介面而已

package com.mybatis.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;

import com.mybatis.bean.Book;

public interface BookMapper extends SqlMapper {

     /**
      * 通過註解方式直接寫程式碼不需要在book-mapper.xml中配置
      * ResultMap對應book-mapper.xml中的(com.mybatis.mapper.BookMapper)為namespace的值 bookResultMap為mybatis檔案中類的別名
      */
     @ResultMap(value="com.mybatis.mapper.BookMapper.bookResultMap")
     @Select("SELECT * FROM book WHERE book_id = #{bookId}")
     public Book findBookById(@Param("bookId") Integer bookId);


//   @ResultMap(value="com.mybatis.mapper.BookMapper.bookResultMap")
//   @Select("SELECT stu.student_id,stu.student_name,stu.student_phone,stu.student_class_id FROM student stu")
//   public List<Student> getStudentList();


     public List<Book> getAllBook();

}

StudentMapper xml 配置

<?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">
<!-- namespace和定義的Mapper介面對應,並實現其中的方法 -->
<mapper namespace="com.mybatis.mapper.StudentMapper">
    <resultMap type="student" id="studentMap">
        <id property="studentId" column="student_id" />
        <result property="studentName" column="student_name" />
        <result property="studentPhone" column="student_phone" />
        <result property="studentClassId" column="student_class_id" />
    </resultMap>

    <!-- id和mapper介面中的方法名對應,parameterType使用mybatis.xml中的別名 -->
    <select id="getAllStudent" parameterType="student" resultMap="studentMap" > 
        <![CDATA[ 
            SELECT * FROM student 
         ]]>
    </select>
    <!--BOOK_SEQUENCE.nextval 為oracle序列 -->
    <insert id="addStudent" parameterType="student"  >
        insert into student(student_id, student_name, student_phone,
        student_class_id)
        values(BOOK_SEQUENCE.nextval, #{studentName}, #{studentPhone}, #{studentClassId})
    </insert>
</mapper>

book xml配置 這裡用純註解所有沒有相關的sql語句也可以新增,靈活開發半註解半sql語句

<?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">
<!-- namespace和定義的Mapper介面對應,並實現其中的方法 ,如果使用@註解方式則不用與介面名全限定名相對應-->
<mapper namespace="com.mybatis.mapper.BookMapper" >
    <resultMap type="book" id="bookResultMap" >
        <id property="bookId" column="book_id"/>
        <result property="bookName" column="book_name"/>
        <result property="bookAuthor" column="book_author"/>
        <result property="bookPrice" column="book_price"/>
    </resultMap>
</mapper>

biz 只是介面

package com.mybatis.biz;

import java.util.List;

import com.mybatis.bean.Book;
import com.mybatis.bean.Student;

public interface CommBiz {

    public Student findStudentById(Integer id);

    public List<Student> findStudentAll();

    public Book findBookById(Integer bookId);


    public void saveStudent(Student stu);

    public List<Student> getAllStudent();

}

biz 實現

package com.mybatis.biz;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mybatis.bean.Book;
import com.mybatis.bean.Student;
import com.mybatis.mapper.BookMapper;
import com.mybatis.mapper.StudentMapper;

@Transactional
@Service
public class CommBizImpl implements CommBiz {

    @Autowired
    private StudentMapper studentMapper;


    @Autowired
    private BookMapper bookMapper;


    @Override
    public Student findStudentById(Integer id) {
        // TODO Auto-generated method stub
        return studentMapper.findStudentById(id);
    }

    @Override
    public Book findBookById(Integer bookId) {
        // TODO Auto-generated method stub
        return bookMapper.findBookById(bookId);
    }


    @Override
    public List<Student> findStudentAll() {
        // TODO Auto-generated method stub
        return studentMapper.getAllStudent();
    }

    public StudentMapper getStudentMapper() {
        return studentMapper;
    }

    public void setStudentMapper(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }



    @Override
    public void saveStudent(Student stu) {
        // TODO Auto-generated method stub
        studentMapper.addStudent(stu);
    }

    @Override
    public List<Student> getAllStudent() {
        // TODO Auto-generated method stub
        return studentMapper.getAllStudent();
    }


}

控制層

package com.mybatis.controller;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.mybatis.bean.Student;
import com.mybatis.biz.CommBiz;

@RequestMapping("front/")
@Controller
public class LoginAction {

    @Autowired
    private CommBiz commBiz;

    @RequestMapping("/login.htm")
    public ModelAndView loginUI(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("test","test");
//      String msg= (String) session.getAttribute("msg");
//      if(msg!=null)
//      mv.addObject("msg",msg);
        mv.setViewName("front/login");
        return mv;

    }

    @RequestMapping("/isLogin")
    public ModelAndView isLogin(String name,String password,HttpSession session){
        ModelAndView mv=new ModelAndView();
        if(name.equals("zengjie")&&password.equals("123456")){
//          mv.addObject("name",name);
            session.setAttribute("name",name);
            mv.setViewName("redirect:main.htm");
        }else{
            mv.addObject("msg","登陸失敗請重新登陸");
            mv.setViewName("redirect:login.htm");
        }
        return mv;
    }

    @RequestMapping("/main.htm")
    public ModelAndView mainUI(){
        ModelAndView mv=new ModelAndView();
        List<Student> stuList=commBiz.findStudentAll();
        mv.addObject("stuList",stuList);
        mv.setViewName("front/main");
        return mv;
    }

}

頁面

<!DOCTYPE html>
<html>
  <head>
    <title>main.html</title>
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="$!webPath/background/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="$!webPath/background/css/bootstrap-responsive.css" />
<script type="text/javascript" src="$!webPath/background/js/jPages/js/jquery-1.8.2.min.js"></script>

<!-- 日期控制元件-->
<script language="javascript" type="text/javascript" src="$!webPath/background/js/WdatePicker.js"></script>
<!-- jpage分頁 -->
<link rel="stylesheet" href="$!webPath/background/js/jPages/css/jPages.css" type="text/css"></link>
<link rel="stylesheet" href="$!webPath/background/js/jPages/css/animate.css" type="text/css"></link>
<script type="text/javascript" src="$!webPath/background/js/jPages/js/jPages.min.js"></script>
<script type="text/javascript">
    $(function() {
        $("div.holder").jPages({
            containerID : "itemContainer",
            previous : "上一頁",
            next : "下一頁",
            perPage : 4
        });

    });
    </script>
  </head>
    <style>
    /*table.gridtable {
        font-family: verdana,arial,sans-serif;
        font-size:14px;
        color:#333333;
        border-width: 1px;
        border-color: #666666;
        border-collapse: collapse;
    }
    table.gridtable th {
        border-width: 1px;
        padding: 8px;
        border-style: solid;
        border-color: #666666;
        background-color: #dedede;
    }
    table.gridtable td {
        border-width: 1px;
        padding: 8px;
        border-style: solid;
        border-color: #666666;
        background-color: #ffffff;
    }*/
    </style>
  <body>
  <br>
    <div align="center">
        <p>學生人員名單  登陸成功歡迎你  <span style="color: red;">$!name</span></p>
        <table class="gridtable table table-bordered table-hover definewidth m10"  style="width: 500px;height: 500px">
            <thead>
                <tr>
                    <th>id</th>
                    <th>姓名</th>
                    <th>電話</th>
                    <th>班級id</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="itemContainer">
                #foreach($stu in $stuList)
                <tr>
                    <td>$!stu.studentId</td>
                    <td>$!stu.studentName</td>
                    <td>$!stu.studentPhone</td>
                    <td>$!stu.studentClassId</td>
                    <td><a href="javascript:deleteNews($!articleList.newsId)"
                            class="btn btn-primary">CRUD</a>  </td>
                </tr>
                #end
            </tbody>
        </table>
        <div align="center" class="holder" style="font-size: 20px"></div>
    </div>
  </body>
</html>

還有mvc的攔截器

package com.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class MyInterceptor implements HandlerInterceptor {



    // afterCompletion()方法在DispatcherServlet完全處理完請求後被呼叫   
    //  這個方法在DispatcherServlet完全處理完請求後被呼叫,可以在該方法中進行一些資源清理的操作。
    public void afterCompletion(HttpServletRequest request,  
            HttpServletResponse response, Object obj, Exception err)  
            throws Exception {  
        request.removeAttribute("status");
    }  
    // postHandle()方法在業務處理器處理請求之後被呼叫 
    //    這個方法在業務處理器處理完請求後,但是DispatcherServlet向客戶端返回請求前被呼叫,在該方法中對使用者請求request進行處理。
    public void postHandle(HttpServletRequest request, HttpServletResponse response,  
            Object obj, ModelAndView mav) throws Exception {  
        String status=(String) request.getAttribute("status");
        String path=mav.getViewName();
        System.out.println(path);
        if(path.contains("login")){
            System.out.println("是登陸請求");
        }else{
            if(status.equals("false")){
                request.getSession().setAttribute("msg", "沒有登入");
                response.sendRedirect("login.htm");
            }
        }

    }  
 // preHandle()方法在業務處理器處理請求之前被呼叫   
//    這個方法在業務處理器處理請求之前被呼叫,
//    在該方法中對使用者請求request進行處理。如果程式設計師決定該攔截器對請求進行攔截處理後還要呼叫其他的攔截器,
//    或者是業務處理器去進行處理,則返回true;如果程式設計師決定不需要再呼叫其他的元件去處理請求,則返回false。
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,  
        Object obj) throws Exception {  
        String str = (String) request.getSession().getAttribute("name");  
        if(str!=null){  
            request.setAttribute("status","true");
        }  else{
            request.setAttribute("status","false");
        }

        return true;  

    }  


}


建議參考 Velocity語法大全
另外還有我的一個專案基於最新的三大框架SSH2.2.3.16+4.0.2+4.3.4 要的留言直接打包給你