参考资料
1 兼顾效率,iBatis一些非见用法(10条)
http://lavasoft.blog.51cto.com/62575/202886/
2 整合Mybatis与Spring3
http://www.iteye.com/topic/1018134
一 环境:XP3+Oracle10g+MyEclipse6+(Tomcat or WebLogic92)+JDK1.5
二 工程文件: Spring3+MyIbatis3
工程图片:
jar下载: http://dl.iteye.com/topics/download/d209389e-ecac-390e-85c7-c08849f50348
三 具体代码如下:
1 数据库文件
create table USERS ( id VARCHAR2(50) not null, name VARCHAR2(50), age INTEGER, sex VARCHAR2(1), address VARCHAR2(200), password VARCHAR2(20) ) insert into users (id,name,age,sex,address,password)VALUES("123456789","sprng",23,"1","北京大学","123");
2 Java相关文件
A UserMapper.java
package com.liuzd.ssm.mapper; import java.util.List; import com.liuzd.ssm.entity.User; public interface UserMapper{ public int checkUserExits(User user); public void addUser(User user); public void editUser(User user); public void delUser(String userId); public List<User> getUserList(); public User getUserByUid(String userId); }
B UserMapper.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"> <mapper namespace="com.liuzd.ssm.mapper.UserMapper"> <resultMap type="com.liuzd.ssm.entity.User" id="userMap"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="age" column="age"/> <result property="sex" column="sex"/> <result property="address" column="address"/> <result property="password" column="password"/> </resultMap> <select id="checkUserExits" parameterType="com.liuzd.ssm.entity.User" resultType="int"> <![CDATA[ select count(*) from users where name=#{name} and password=#{password} ]]> </select> <select id="getUserList" resultType="java.util.List" resultMap="userMap"> <![CDATA[ select * from users ]]> </select> <select id="getUserByUid" parameterType="string" resultType="com.liuzd.ssm.entity.User"> <![CDATA[ select * from users where id=#{id} ]]> </select> <update id="editUser" parameterType="com.liuzd.ssm.entity.User"> <![CDATA[ update users set name=#{name},age=#{age},sex=#{sex},address=#{address},password=#{password} where id=#{id} ]]> </update> <insert id="addUser" parameterType="com.liuzd.ssm.entity.User"> <![CDATA[ insert into users (id,name,age,sex,address,password)VALUES(#{id},#{name},#{age},#{sex},#{address},#{password}) ]]> </insert> <delete id="delUser" parameterType="string"> <![CDATA[ delete users where id=#{id} ]]> </delete> </mapper>
C UserService.java
package com.liuzd.ssm.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.liuzd.ssm.entity.User; import com.liuzd.ssm.mapper.UserMapper; @Service("userService") public class UserService { @Autowired private UserMapper userMapper; public void addUser(User user) { this.userMapper.addUser(user); } public int checkUserExits(User user) { return this.userMapper.checkUserExits(user); } public void delUser(String userId) { this.userMapper.delUser(userId); } public User getUserByUid(String userId) { return (User)this.userMapper.getUserByUid(userId); } public List<User> getUserList() { return (List<User>)this.userMapper.getUserList(); } public void editUser(User user) { this.userMapper.editUser(user); } }
D WEB层调用代码
a LoginController.java
package com.liuzd.ssm.web; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.liuzd.ssm.entity.User; import com.liuzd.ssm.service.UserService; @Controller @RequestMapping("/login") public class LoginController { private UserService userService; public UserService getUserService() { return userService; } @Resource public void setUserService(UserService userService) { this.userService = userService; } @SuppressWarnings("unchecked") @RequestMapping("add") //@ModelAttribute 可加可不加,url: http://127.0.0.1:8088/ssm/user/add.do public String login(User user, HttpServletRequest req, HttpServletResponse response) { // 此处调用服务层进行相应的业务操作 // 传递对象于下一页面 req.setAttribute("user", user); // 调用服务层进行验证用户,此处只演示功能 int usize = getUserService().checkUserExits(user); System.out.println("用户信息: " + user + ",usize: "+usize); if (usize > 0) { //return "success"; List<User> useralls = this.getUserService().getUserList(); req.setAttribute("userList", useralls); return "userList"; } return "error"; } @SuppressWarnings("unchecked") // @RequestMapping(params= "method=add2",method=RequestMethod.POST) // 定义method方法不是必须的 @RequestMapping(params = "method=add2") public ModelAndView login2(@ModelAttribute("user")User user, HttpServletRequest req, HttpServletResponse response) { // 使用ModelAndView保存对象于下一页面 ModelAndView model = new ModelAndView(); model.addObject("user", user); // 调用服务层进行验证用户,此处只演示功能 int usize = getUserService().checkUserExits(user); System.out.println("用户信息2: " + user + ",usize: "+usize); if (usize > 0) { List<User> useralls = this.getUserService().getUserList(); model.addObject("userList", useralls); model.setViewName("userList"); } else { model.addObject("msg","用户或者密码错误!"); model.setViewName("error"); } return model; } @RequestMapping(value="add3/{name}/{password}",method=RequestMethod.GET) public String login3(@PathVariable("name") String name,@PathVariable("password") String pwd,Model model) { User user = new User(); user.setName(name); user.setPassword(pwd); model.addAttribute("user",user); // 调用服务层进行验证用户,此处只演示功能 int usize = getUserService().checkUserExits(user); System.out.println("用户信息3: "+user + ",size: " + usize); if (usize > 0) { return "success"; } //放入model默认把参数存于请求 model.addAttribute("msg","用户或者密码错误!"); return "error"; /** * 重定向JSP页面,走出了springmvc配置的view(jsp) * 因为这样说明:model.addAttribute("msg","用户或者密码错误!"); * 获取不到值了 * 不加上.jsp就是这样:http://127.0.0.1:8080/Spring3-Login-Annotaction/index?msg=%E7... * */ //返回到页面是乱码在页面中用${msg}获取不到值,用request.getParams("msg");为乱码 //return "redirect:index.jsp?msg=用户或者密码错误!"; } }
b UserController.java
package com.liuzd.ssm.web; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; import com.liuzd.ssm.entity.User; import com.liuzd.ssm.service.UserService; @Controller @RequestMapping("/user") @SessionAttributes("userList") public class UserController { private UserService userService; public UserService getUserService() { return userService; } @Resource public void setUserService(UserService userService) { this.userService = userService; } @RequestMapping("/userList") public ModelAndView userList(){ /** * 想要在页面展现数据,必须返回ModelAndView类型,返回String是不能获取数据的 * */ ModelAndView mv = new ModelAndView(); List<User> users = this.getUserService().getUserList(); mv.addObject("userList",users); mv.setViewName("userList"); return mv; } @RequestMapping("/addUser") public ModelAndView addUser(User user){ System.out.println("ADD USER: "+ user); this.userService.addUser(user); return userList(); } @RequestMapping("/toAddUser") public String toAddUser(){ return "addUser"; } @RequestMapping("/delUser/{id}") public ModelAndView delUser(@PathVariable("id") String id){ this.userService.delUser(id); return userList(); } @RequestMapping("/getUser/{id}") public ModelAndView getUser(@PathVariable("id") String id){ User user = this.userService.getUserByUid(id); ModelAndView mv = new ModelAndView("updateUser"); mv.addObject("user",user); return mv; } @RequestMapping("/updateUser") public ModelAndView editUser(User user){ System.out.println("编辑: "+user); this.userService.editUser(user); return userList(); } }
3 JSp文件
A index.jsp
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <%@ include file="/common/meta.jsp"%> </head> <body> <form action="${pageContext.request.contextPath}/login/add.do" method="post"> 姓名: <input type="text" name="name" id="name"><br> 密码: <input type="password" name="password" id="password"><br> <input type="submit" value="Login"> </form> <br> <form action="${pageContext.request.contextPath}/login.do?method=add2" method="post"> 姓名: <input type="text" name="name" id="name"><br> 密码: <input type="password" name="password" id="password"><br> <input type="submit" value="Login2"> </form> <br> <a href="${pageContext.request.contextPath}/login/add3/spring/spring.do">Spring MVC RESL风格</a> </body> </html>
B addUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="org.apache.commons.lang3.RandomStringUtils"%> <% String id = RandomStringUtils.randomAlphanumeric(32); %> <html> <head> <title>用户信息</title> </head> <body> <form action="${pageContext.request.contextPath}/user/addUser.do" method="post"> <br> <table> <tr> <td> <input name="id" type="hidden" value="<%=id%>"> 姓名: <input name="name"> </td> </tr> <tr> <td> 年龄: <input name="age"> </td> </tr> <tr> <td> 性别: <select name="sex"> <option value="1">男</option> <option value="2">女</option> </select> </td> </tr> <tr> <td> 密码: <input name="password"> </td> </tr> <tr> <td> 地址:<input name="address"/> </td> </tr> <tr> <td align="right"> <input type="submit" vlaue="保存"/> </td> </tr> </table> </form> <br> <a href="${pageContext.request.contextPath}/index.jsp">返回主页</a><br> <a href="${pageContext.request.contextPath}/user/userList.do">返回显示</a> </body> </html>
C updateUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <title>编辑用户信息</title> </head> <body> <form action="${pageContext.request.contextPath}/user/updateUser.do" method="post"> <br> <table> <tr> <td> <input name="id" type="hidden" value="${user.id}"> 姓名: <input name="name" value="${user.name}"> </td> </tr> <tr> <td> 年龄: <input name="age" value="${user.age}"> </td> </tr> <tr> <td> 性别: <select name="sex"> <option value="1" ${user.sex eq "1" ? "selected" : ""}>男</option> <option value="2" ${user.sex eq "2" ? "selected" : ""}>女</option> </select> </td> </tr> <tr> <td> 密码: <input name="password" value="${user.password}"> </td> </tr> <tr> <td> 地址:<input name="address" value="${user.address}"/> </td> </tr> <tr> <td align="right"> <input type="submit" vlaue="保存"/> </td> </tr> </table> </form> <br> <a href="${pageContext.request.contextPath}/index.jsp">返回主页</a><br> <a href="${pageContext.request.contextPath}/user/userList.do">返回集合显示</a> </body> </html>
D userList.jsp
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> <%@ taglib uri="/WEB-INF/c.tld" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <%@ include file="/common/meta.jsp"%> </head> <body> <table width="60%" border="1" cellpadding="0" align="center"> <thead> <tr> <th style="cursor: hand;" title="按姓名进行排序" onclick="sortPage('name')" valign="top"> 姓名 </th> <th style="cursor: hand;" title="按年龄进行排序" onclick="sortPage('age')" valign="top"> 年龄 </th> <th style="cursor: hand;" title="按性别进行排序" onclick="sortPage('sex')" valign="top"> 性别 </th> <th style="cursor: hand;" title="按地址进行排序" onclick="sortPage('address')" valign="top"> 地址 </th> <th style="cursor: hand;" > 操作 </th> </tr> </thead> <tbody> <c:forEach items="${userList}" var="user"> <tr align="center"> <td> ${user.name} </td> <td> ${user.age} </td> <td> ${user.sex eq 1 ? "男" : user.sex eq 2 ? "女" : "未知"} </td> <td> ${user.address} </td> <td> <a href="${pageContext.request.contextPath}/user/toAddUser.do">添加</a> | <a href="${pageContext.request.contextPath}/user/getUser/${user.id}.do">编辑</a> | <a href="${pageContext.request.contextPath}/user/delUser/${user.id}.do">删除</a> </td> </tr> </c:forEach> </tbody> </table> <br> <a href="${pageContext.request.contextPath}/index.jsp">返回</a> </body> </html>
4 配置文件
a web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>webAppRootKey</param-name> <param-value>ssm.root</param-value> </context-param> <context-param> <param-name> contextConfigLocation </param-name> <param-value> classpath*:applicationContext.xml </param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <context-param> <param-name>log4jExposeWebAppRoot</param-name> <param-value>false</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.util.Log4jConfigListener </listener-class> </listener> <filter> <filter-name>encodingFilter</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>false</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <servlet> <servlet-name>springmvc</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>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- weblogic配置数据源需要 <resource-ref> <description>s2sh</description> <res-ref-name>s2sh</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
b applicationContext.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:annotation-config /> <context:component-scan base-package="com.liuzd.ssm.service" /> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:jdbc.properties</value> </property> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <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="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>${JNDI}</value> </property> <property name="resourceRef"> <value>${RESOURCEREF}</value> </property> <property name="jndiEnvironment"> <props> <prop key="java.naming.provider.url">${Context.PROVIDER_URL}</prop> <prop key="java.naming.factory.initial">${Context.INITIAL_CONTEXT_FACTORY}</prop> </props> </property> </bean> --> <!-- define the SqlSessionFactory, notice that configLocation is not needed when you use MapperFactoryBean --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- <property name="configLocation" value="classpath*:mybatis-config.xml"/> --> </bean> <!-- scan for mappers and let them be autowired --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.liuzd.ssm.mapper" /> </bean> </beans>