上次介绍了用接口的方法极大的节省了dao层,只需通过 配置文件和接口就可以实现,这次介绍的是通过splsession来实现dao,这种方法比较灵活;
先不说,上配置文件:
1、web.xml
<?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>
2、application.xml
<?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.xml
<?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>
4、相关配置文件
jdbc.properties
jdbcUrl=jdbc:mysql://localhost:3306/db_articlemanage
driverClass=com.mysql.jdbc.Driver
user=root
password=root
5、javabean
例如User
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; } }
8、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; } }
9、通过以上配置与实现,我们就可以很简单的操作数据库了:
其中查询帮助类是用来帮助查询,其原理就是拼接命名空间,设置参数,方便查询
例如,查询分页数据
/** * 获取分页数据. * @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; }
天生不会写东西,但是很想分享给大家,有什么问题请大家指出!