springmvc與mybatis結合

之前寫了一篇springmvc的環境搭建,現在寫與mybatis相結合
http://blog.csdn.net/nmj2015/article/details/72288428
一. 基於前次的目錄結構,我們在新建config中新建jdbc.properties與spring-myatis.xml並在springmvc.xml中添加引用語句

driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
username=one_user
password=123
#定義初始連接數  
initialSize=0  
#定義最大連接數  
maxActive=20  
#定義最大空閒  
maxIdle=20  
#定義最小空閒  
minIdle=1  
#定義最長等待時間  
maxWait=60000  
<?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:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  



    <!-- 自動掃描 -->  
    <context:component-scan base-package="eesofa.cn.dao" />  
    <!-- 引入配置文件 -->  
    <bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:jdbc.properties" />  
    </bean>  

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">  
        <property name="driverClassName" value="${driver}" />  
        <property name="url" value="${url}" />  
        <property name="username" value="${username}" />  
        <property name="password" value="${password}" />  
        <!-- 初始化連接大小 -->  
        <property name="initialSize" value="${initialSize}"></property>  
        <!-- 連接池最大數量 -->  
        <property name="maxActive" value="${maxActive}"></property>  
        <!-- 連接池最大空閒 -->  
        <property name="maxIdle" value="${maxIdle}"></property>  
        <!-- 連接池最小空閒 -->  
        <property name="minIdle" value="${minIdle}"></property>  
        <!-- 獲取連接最大等待時間 -->  
        <property name="maxWait" value="${maxWait}"></property>  
    </bean>  

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- 自動掃描mapping.xml文件 -->  
        <property name="mapperLocations" value="classpath:eesofa/cn/mapper/*.xml"></property>  
    </bean>  

    <!-- DAO接口所在包名,Spring會自動查找其下的類 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="eesofa.cn.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>  

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->  
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  
</beans>  
    <!-- 加載mybatis配置文件 -->
    <import resource="classpath:spring-mybatis.xml" />

二.在數據庫中新建表並添加數據,語句如下

create table PRIV_USER  
    (  
      USER_ID    NUMBER not null,  
      USER_NAME    VARCHAR2(30),  
      PASSWORD    VARCHAR2(30),  
      NAME    VARCHAR2(30),  
      SEX     VARCHAR2(3),  
      CID    VARCHAR2(30),    
      PHONE VARCHAR2(50),
      MAIL VARCHAR2(50),
      GETTIME DATE,
      ABOUT CLOB
    );  
      commit;
    create sequence SEQ_USER_ID  
    minvalue 0  
    maxvalue 99999999  
    start with 0  
    increment by 1  
    cache 20;  
  commit;
insert into PRIV_USER(user_id,user_name,PASSWORD,name,sex,cid,phone,mail,gettime,about)
        values(SEQ_USER_ID.nextval,'張三','張小三','uiy','男','uiy','17318187632','[email protected]',sysdate,'無限大');
insert into PRIV_USER(user_id,user_name,PASSWORD,name,sex,cid,phone,mail,gettime,about)
        values(SEQ_USER_ID.nextval,'李四','李四三','uiy','女','usdasdasdasdiy','18519220228','[email protected]',sysdate,'你覺得多大');
    commit;

三.在bean中新建Priv_User和在dao中建立Priv_UserDao的查詢方法

package eesofa.cn.bean;  

import java.util.Date;

/**  
 * 類說明   
 *  
 * @author nmj
 * @email  [email protected]
 * @date 2017年5月16日  新建  
 */
public class Priv_User {
    private Integer user_id;
    private String user_name;
    private String password;
    private String name;
    private String sex;
    private String cid;
    private String phone;
    private String mail;
    private Date gettime;
    private String about;
    public Integer getUser_id() {
        return user_id;
    }
    public void setUser_id(Integer user_id) {
        this.user_id = user_id;
    }
    public String getUser_name() {
        return user_name;
    }
    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getCid() {
        return cid;
    }
    public void setCid(String cid) {
        this.cid = cid;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getMail() {
        return mail;
    }
    public void setMail(String mail) {
        this.mail = mail;
    }
    public Date getGettime() {
        return gettime;
    }
    public void setGettime(Date gettime) {
        this.gettime = gettime;
    }
    public String getAbout() {
        return about;
    }
    public void setAbout(String about) {
        this.about = about;
    }
    @Override
    public String toString() {
        return "Priv_User [user_id=" + user_id + ", user_name=" + user_name
                + ", password=" + password + ", name=" + name + ", sex=" + sex
                + ", cid=" + cid + ", phone=" + phone + ", mail=" + mail
                + ", gettime=" + gettime + ", about=" + about + "]";
    }
    public Priv_User() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Priv_User(Integer user_id, String user_name, String password,
            String name, String sex, String cid, String phone, String mail,
            Date gettime, String about) {
        super();
        this.user_id = user_id;
        this.user_name = user_name;
        this.password = password;
        this.name = name;
        this.sex = sex;
        this.cid = cid;
        this.phone = phone;
        this.mail = mail;
        this.gettime = gettime;
        this.about = about;
    }


}

package eesofa.cn.dao;  

import eesofa.cn.bean.Priv_User;


/**  
 * 類說明   
 *  
 * @author nmj
 * @email  [email protected]
 * @date 2017年5月16日  新建  
 */
@Component("priv_UserDao")
public interface Priv_UserDao {

    /***
     * 根據user_id查詢Priv_User信息
     * @param user_id
     * @return
     */
    public Priv_User queryByUserId(Object user_id); 

}

四.實現dao的mapper,根據自己的需要修改。

<?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">
<!--這塊等於dao接口的實現 namespace必須和接口的類路徑一樣 -->
<mapper namespace="eesofa.cn.dao.Priv_UserDao">

    <!-- Result Map -->
    <resultMap type="eesofa.cn.bean.Priv_User" id="BaseResultMap">
        <result property="user_id" column="user_id" />
        <result property="user_name" column="user_name" />
        <result property="password" column="password" />
        <result property="name" column="name" />
        <result property="sex" column="sex" />
        <result property="cid" column="cid" />
        <result property="phone" column="phone" />
        <result property="mail" column="mail" />
        <result property="gettime" column="gettime" jdbcType="TIMESTAMP" />
        <result property="about" column="about" jdbcType="CLOB"
            javaType="java.lang.String" typeHandler="eesofa.cn.util.OracleClobTypeHandler" />
    </resultMap>

    <!-- 表名 -->
    <sql id="Tabel_Name">
        PRIV_USER
    </sql>

    <!-- 表中所有列 -->
    <sql id="Base_Column_List">
    user_id,user_name,password,name,sex,cid,phone,mail,gettime,about
    </sql>

    <!-- 查詢條件 -->
    <sql id="Example_Where_Clause">
        where 1=1
        <trim suffixOverrides=",">
            <if test="user_id != null">
                and user_id = #{user_id}
            </if>
            <if test="user_name != null and user_name != ''">
                and user_name like concat(concat('%', '${user_name}'), '%')
            </if>
            <if test="password != null and password != ''">
                and password like concat(concat('%', '${password}'), '%')
            </if>
            <if test="name != null and name != ''">
                and name like concat(concat('%', '${name}'), '%')
            </if>
            <if test="sex != null and sex != ''">
                and sex like concat(concat('%', '${sex}'), '%')
            </if>
            <if test="cid != null and cid != ''">
                and cid like concat(concat('%', '${cid}'), '%')
            </if>
            <if test="phone != null and phone != ''">
                and phone like concat(concat('%', '${phone}'), '%')
            </if>
            <if test="mail != null and mail != ''">
                and mail like concat(concat('%', '${mail}'), '%')
            </if>
            <if test="gettime != null and gettime != ''">
                and gettime like concat(concat('%', '${gettime}'), '%')
            </if>
            <if test="about != null and about != ''">
                and about like concat(concat('%', '${about}'), '%')
            </if>
        </trim>
    </sql>

    <!-- 下面的id都和接口Priv_UserDao中的方法名一樣 -->
        <!-- 根據user_id查詢 -->
    <select id="queryByUserId" resultMap="BaseResultMap" parameterType="Object">
        select
        <include refid="Base_Column_List" />
        from PRIV_USER where user_id = #{user_id}
    </select>

    </mapper>

五.在eesofa.test目錄下新建test_mybatis.java來測試查詢語句

package eesofa.test;  

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import eesofa.cn.bean.Priv_User;
import eesofa.cn.dao.Priv_UserDao;

/**  
 * 類說明   
 *  
 * @author nmj
 * @email  [email protected]
 * @date 2017年5月16日  新建  
 */
public class test_mybatis {

    @Test
    public void testMybits(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext(
                new String[] { "spring-mybatis.xml" });
        Priv_UserDao dao = (Priv_UserDao)ctx.getBean("priv_UserDao");
        try {
            System.out.println(dao.queryByUserId(2).toString());
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.getMessage());
        }
    }
}

—end

發佈了37 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章