上次介紹了用接口的方法極大的節省了dao層,只需經過 配置文件和接口就能夠實現,此次介紹的是經過splsession來實現dao,這種方法比較靈活;html
先不說,上配置文件:java
一、web.xmlmysql
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <!--引入spring--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application.xml</param-value> </context-param> <!--springmvc DispathcherServlet--> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> </web-app>
二、application.xmlweb
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" 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"> <!--spring註解--> <context:component-scan base-package="com.seven"/> <!-- 導入外部的配置文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!--數據源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbcUrl}"/> <property name="driverClass" value="${driverClass}"/> <property name="user" value="${user}"/> <property name="password" value="${password}"/> </bean> <!--mybatis 的 sqlsessionFactoryNean--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- <property name="configLocation" value="classpath:conf.xml"/>--> <property name="mapperLocations" value="classpath:com/seven/dao/*.xml"/> <property name="typeAliasesPackage" value="com.seven.domain"/><!--指定實體類包,自動將實體類的簡單類名映射爲別名--> </bean> <!--映射器接口 有了 下面配置就不用了--> <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> <property name="mapperInterface" value="com.seven.dao.UserMapper"/> </bean>--> <!--mybatis自動掃描加載映射接口:mapperScannerConfigurer--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.seven.dao"/><!--指定映射接口所在的包--> <!-- <property name="sqlSessionFactory" ref="sqlSessionFactory"/>--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!--事務管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- <context:component-scan base-package="com.seven.*"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>--> <!--聲明事務--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
3.sprin-mvc.xmlspring
<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--spring註解掃描包--> <context:component-scan base-package="com.seven"/> <!--springmvc註解驅動--> <mvc:annotation-driven/> <!-- 資源管理 --> <mvc:resources location="/resources/" mapping="/resources/**"/> <mvc:resources location="/upload/" mapping="/upload/**"/> <!-- 上傳文件解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485670"/> <!-- 10M --> </bean> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/admin/**"/> <mvc:exclude-mapping path="/admin/loginUI.action"/> <mvc:exclude-mapping path="/admin/managerLogin.action"/> <mvc:exclude-mapping path="/admin/validateManager.action"/> <bean class="com.seven.interceptor.CheckLoginInterceptor"/> </mvc:interceptor> </mvc:interceptors> <!--內部資源解析器--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".html"/> </bean> </beans>
四、相關配置文件sql
jdbc.properties數據庫
jdbcUrl=jdbc:mysql://localhost:3306/db_articlemanage
driverClass=com.mysql.jdbc.Driver
user=root
password=root
五、javabeanexpress
例如Userapache
package com.seven.domain; import org.apache.ibatis.type.Alias; import java.io.Serializable; import java.util.Set; /** * Created by Seven on 2015/5/29. */ public class User implements Serializable{ private Long id; private String loginname; private String username; private String password; private String intro; private Set<Role> roles; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLoginname() { return loginname; } public void setLoginname(String loginname) { this.loginname = loginname; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getIntro() { return intro; } public void setIntro(String intro) { this.intro = intro; } public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } }
User對應的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"> <!--使用mapper編程的時候,namespace必須是接口的全類名 --> <mapper namespace="User"> <!--user結果映射--> <resultMap id="userResult" type="User"> <result column="id" property="id"/> <result column="loginname" property="loginname"/> <result column="username" property="username"/> <result column="password" property="password"/> <result column="intro" property="intro"/> </resultMap> <!-- 取得插入數據後的id --> <insert id="insert" parameterType="map"> insert into tb_user(loginname,username,password,intro) values(#{loginname},#{username},#{password},#{intro}) </insert> <update id="update"> update tb_user set loginname = #{loginname}, username = #{username}, password = #{password}, intro = #{intro} where id = #{id} </update> <delete id="delete"> delete from tb_user where id = #{id} </delete> <select id="findById" resultMap="userResult"> select * from tb_user where id = #{id} </select> <select id="findAll" resultMap="userResult"> select * from tb_user </select> <select id="findByIds" resultMap="userResult"> select * from tb_user where id IN (#{ids}) </select> <select id="getPage" resultMap="userResult" parameterType="map"> select * from tb_user LIMIT #{startIndex},#{pageSize} </select> <select id="findByloginnameAndPwd" resultMap="userResult"> SELECT * FROM tb_user WHERE loginname=#{loginname} AND password=#{password} </select> </mapper>
7.queryhepler
package com.seven.utils; import java.util.HashMap; import java.util.Map; /** * Created by Seven on 2015/6/12. */ public class QueryHelper { private String nameSpace; private String methodId; private Object param; private Map<String,Object> params; /** * 設置命名空間. * @param nameSpace * @return */ public QueryHelper setNameSpace(String nameSpace){ this.nameSpace = nameSpace; return this; } /** * 設置dao方法的ID. * @param methodId * @return */ public QueryHelper setMethodId(String methodId){ this.methodId = methodId; return this; } /** * 設置一個參數. * @param param * @return */ public QueryHelper setParam(Object param){ this.param = param; return this; } /** * 設置多個參數. * @param key * @param value * @return */ public QueryHelper setParams(String key,Object value){ if(params == null){ params = new HashMap<String, Object>(); } params.put(key,value); return this; } /** * 獲取一個參數. * @return */ public Object getParam(){ return param; } /** * 得到多個參數. * @return */ public Map<String,Object> getParams(){ return params; } /** * 獲取非空的參數. * @return */ public Object getRealParams(){ return param == null ? params : param; } /** * 獲得結果. * @return */ public String getMethod(){ return nameSpace+"."+methodId; } }
八、daoSupport和daoSupportImpl
daosupport
package com.seven.base; import com.seven.utils.QueryHelper; import java.util.List; import java.util.Map; /** * Created by Seven on 2015/6/12. */ public interface DaoSupport { public void insert(QueryHelper queryHelper); public void insert(String method,Object param); public void delete(QueryHelper queryHelper); public void delete(String method,Object o); public void update(QueryHelper queryHelper); public void update(String method,Object o); public<T> T select(QueryHelper queryHelper); public<T> T select(String method,Object o); public<T> List<T> selectList(QueryHelper queryHelper); public<T> List<T> selectList(String method,Object o); public<T> List<T> getPageData(int pageNum,int pageSize,QueryHelper queryHelper); }
daosupportImpl
package com.seven.base; import com.seven.utils.QueryHelper; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.lang.reflect.ParameterizedType; import java.util.List; import java.util.Map; /** * Created by Seven on 2015/6/12. */ @Repository("daoSupport") @Transactional public class DaoSupportImpl implements DaoSupport{ @Resource private SqlSessionFactory sqlSessionFactory; private SqlSession sqlSession = null; /** * 獲取sqlSession. * @return */ public SqlSession getSqlSession(){ if(sqlSession==null){ sqlSession = sqlSessionFactory.openSession(); } return sqlSession; } /** * 插入. * @param queryHelper */ public void insert(QueryHelper queryHelper) { getSqlSession().insert(queryHelper.getMethod(),queryHelper.getRealParams()); } /** * 插入. * @param method * @param param */ public void insert(String method, Object param) { getSqlSession().insert(method,param); } /** * 刪除. * @param queryHelper */ public void delete(QueryHelper queryHelper) { getSqlSession().delete(queryHelper.getMethod(),queryHelper.getRealParams()); } /** * 刪除. * @param method * @param o */ public void delete(String method, Object o) { getSqlSession().delete(method,o); } /** * 更新. * @param queryHelper */ public void update(QueryHelper queryHelper) { getSqlSession().update(queryHelper.getMethod(),queryHelper.getRealParams()); } /** * 更新. * @param method * @param o */ public void update(String method, Object o) { getSqlSession().update(method,o); } /** * 查找一個. * @param queryHelper * @param <T> * @return */ public <T> T select(QueryHelper queryHelper) { return getSqlSession().selectOne(queryHelper.getMethod(),queryHelper.getRealParams()); } /** * 查找一個. * @param method * @param o * @param <T> * @return */ public <T> T select(String method, Object o) { return getSqlSession().selectOne(method,o); } /** * 查找多個. * @param queryHelper * @param <T> * @return */ public <T> List<T> selectList(QueryHelper queryHelper) { return getSqlSession().selectList(queryHelper.getMethod(),queryHelper.getRealParams()); } /** * 查找多個. * @param method * @param o * @param <T> * @return */ public <T> List<T> selectList(String method, Object o) { return getSqlSession().selectList(method,o); } /** * 查找全部. * @param method * @param <T> * @return */ public <T> List<T> selectWithoutParams(String method) { return getSqlSession().selectList(method); } /** * 分頁數據. * @param pageNum * @param pageSize * @param queryHelper * @param <T> * @return */ public <T> List<T> getPageData(int pageNum, int pageSize, QueryHelper queryHelper) { return null; } }
九、經過以上配置與實現,咱們就能夠很簡單的操做數據庫了:
其中查詢幫助類是用來幫助查詢,其原理就是拼接命名空間,設置參數,方便查詢
例如,查詢分頁數據
/** * 獲取分頁數據. * @param pageNum * @return */ public Page getPageData(int pageNum){ int totleRecord = daoSupport.select("Article.getTotleRecord",null); Page page = new Page(pageNum, Configuration.pageSize,totleRecord); QueryHelper helper = new QueryHelper(); helper.setNameSpace("Article") .setMethodId("getPageData") .setParams("startIndex",page.getStartIndex()) .setParams("pageSize",page.getPageSize()); List list = daoSupport.selectList(helper); page.setList(list); return page; }
天生不會寫東西,可是很想分享給你們,有什麼問題請你們指出!