springmvc+MyBatis简单CRUD

实体类:Student.java
package demo.entity;

public class Student extends BaseEntity
{
    private int id;
    
    private String name;
    
    private String sex;
    
    private String address;
    
    public int getId()
    {
        return id;
    }
    
    public void setId(int id)
    {
        this.id = id;
    }
    
    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 getAddress()
    {
        return address;
    }
    
    public void setAddress(String address)
    {
        this.address = address;
    }
}


BaseEntity.java(可扩展,加入分页基本参数)
package demo.entity;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class BaseEntity
{   
    public String toString()
    {
        //得到类中的成员变量
        Field[] fields = this.getClass().getDeclaredFields();
        StringBuffer strBuf = new StringBuffer();
        for(int i=0; i<fields.length; i++)
        {
           //成员变量名称
            String fieldName = fields[i].getName();
            //拼接出方法名:getXxx()
            String methodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
            try
            {
                //得到方法
                Method method = this.getClass().getMethod(methodName, new Class[]{});
                //调用方法
                Object value = method.invoke(this, new Object[]{});
                strBuf.append(fieldName + ":");
                strBuf.append(value + "  ");
            }
            catch (SecurityException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (NoSuchMethodException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IllegalArgumentException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IllegalAccessException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (InvocationTargetException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return strBuf.toString();
    }
}

==============================
IStudentDao.java
package demo.dao;

import java.util.List;

import demo.entity.Student;

public interface IStudentDao
{
    public boolean insert(Student stu);
    
    public boolean delete(int id);
    
    public boolean update(Student stu);
    
    public List<Student> findAll();
    
    public Student findById(int id);
}


StudentDaoImpl.java
package demo.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;

import demo.dao.IStudentDao;
import demo.entity.Student;

@SuppressWarnings("unchecked")
public class StudentDaoImpl implements IStudentDao
{
    /*sql 语句*/
    private static final String INSERT = "insert";
    
    private static final String UPDATE = "update";
    
    private static final String DELETE = "delete";
    
    private static final String SELECTALL = "selectAll";
    
    private static final String SELECTBYID = "selectById";
    
    private SqlSessionTemplate sqlSession;
    
    @Resource
    public void setSqlSession(SqlSessionTemplate sqlSession)
    {
        this.sqlSession = sqlSession;
    }
    
    public boolean delete(int id)
    {
        // TODO Auto-generated method stub
        String sql = this.getStatementId(Student.class, DELETE);
        sqlSession.delete(sql, id);
        return true;
    }
    
    public List<Student> findAll()
    {
        // TODO Auto-generated method stub
        String sql = this.getStatementId(Student.class, SELECTALL);
        List<Student> list = (List<Student>)sqlSession.selectList(sql);
        return list;
    }
    
    public Student findById(int id)
    {
        // TODO Auto-generated method stub
        String sql = this.getStatementId(Student.class, SELECTBYID);
        Student stu = (Student)sqlSession.selectOne(sql, id);
        return stu;
    }
    
    @SuppressWarnings("static-access")
    public boolean insert(Student stu)
    {
        // TODO Auto-generated method stub
        String sql = this.getStatementId(Student.class, INSERT);
        this.sqlSession.insert(sql, stu);
        return true;
    }
    
    public boolean update(Student stu)
    {
        // TODO Auto-generated method stub
        String sql = this.getStatementId(Student.class, UPDATE);
        this.sqlSession.update(sql, stu);
        return true;
    }
    
    /**  
     * 映射sqlid
     */
    private String getStatementId(Class entityClass, String suffix)
    {
        String sqlStr = entityClass.getName() + "." + suffix;
        System.out.println("getStatementId:" + sqlStr);
        return sqlStr;
    }
    
}

==============
IStudentService.java
package demo.service;

import java.util.List;

import demo.entity.Student;

public interface IStudentService
{
public boolean insert(Student stu);
    
    public boolean delete(int id);
    
    public boolean update(Student stu);
    
    public List<Student> findAll();
    
    public Student findById(int id);
}

StudentServiceImpl.java
package demo.service.impl;

import java.util.List;

import javax.annotation.Resource;

import demo.dao.IStudentDao;
import demo.entity.Student;
import demo.service.IStudentService;

public class StudentServiceImpl implements IStudentService
{
    private IStudentDao stuDao;
    @Resource
    public void setStuDao(IStudentDao stuDao)
    {
        this.stuDao = stuDao;
    }

    public boolean delete(int id)
    {
        // TODO Auto-generated method stub
        return stuDao.delete(id);
    }

    public List<Student> findAll()
    {
        // TODO Auto-generated method stub
        return stuDao.findAll();
    }

    public Student findById(int id)
    {
        // TODO Auto-generated method stub
        return stuDao.findById(id);
    }

    public boolean insert(Student stu)
    {
        // TODO Auto-generated method stub
        stuDao.insert(stu);
        return true;
    }

    public boolean update(Student stu)
    {
        // TODO Auto-generated method stub
        return stuDao.update(stu);
    }
    
}

===================
StudentInfoMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="demo.entity.Student">
	<!-- 
		起别名 
		<alias>
			<typeAlias alias="" type="" />
		</alias>
	-->
	<!-- useGeneratedKeys="true" keyProperty="xxx" for sqlserver and mysql -->
    <insert id="insert" parameterType="demo.entity.Student" useGeneratedKeys="true" keyProperty="id">
    <![CDATA[
        INSERT INTO
        student (
        	name,
        	sex,
        	address
        ) VALUES (
        	#{name,jdbcType=VARCHAR},
        	#{sex,jdbcType=VARCHAR},
        	#{address,jdbcType=VARCHAR}
        )
    ]]>
		<!--	
			oracle: order="BEFORE" SELECT sequenceName.nextval AS ID FROM DUAL 
			DB2: order="BEFORE"" values nextval for sequenceName
		<selectKey resultType="java.lang.Long" order="BEFORE" keyProperty="userId">
			SELECT sequenceName.nextval AS ID FROM DUAL 
        </selectKey>
		-->
    </insert>
    
    <update id="update" parameterType="demo.entity.Student">
    <![CDATA[
        UPDATE student SET
	        name = #{name,jdbcType=VARCHAR},
	        sex = #{sex,jdbcType=VARCHAR},
	        address = #{address,jdbcType=VARCHAR}
        WHERE 
	        id = #{id,jdbcType=INTEGER} 
    ]]>
    </update>

    <delete id="delete" parameterType="demo.entity.Student">
        delete from student where
        id = #{id}
    </delete>

    <select id="selectById" resultType="demo.entity.Student" parameterType="Integer">
		select *
		    from student
	        where id = #{id}
    </select>
	
	 <select id="selectAll" resultType="demo.entity.Student">
		select * from student;
    </select>
	
    <delete id="deleteByPrimaryKey" parameterType="Integer">
        delete from student where
        id = #{id}
    </delete>
</mapper>

================
StudentController.java
package demo.controller;

import java.util.List;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import demo.entity.Student;
import demo.service.IStudentService;

@Controller
@RequestMapping("/student")
public class StudentController
{
    private static final Log log = LogFactory.getLog(StudentController.class);
    
    private IStudentService stuService;
    
    @Resource
    public void setStuService(IStudentService stuService)
    {
        this.stuService = stuService;
    }
    
    /**
     * 增
     */
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public String insert(HttpServletRequest request,
            HttpServletResponse response, Student stu)
    {
        stuService.insert(stu);
        log.info(stu);
        return "redirect:/student/allStudent.do";
    }
    
    /**
     * 删
     */
    @RequestMapping("/delete/{id}")
    public String delete(HttpServletRequest request,
            HttpServletResponse response, @PathVariable("id")
            int id)
    {
        stuService.delete(id);
        return "redirect:/student/allStudent.do";
    }
    
    /**
     * 得到所有
     */
    @RequestMapping("/allStudent")
    public ModelAndView allStudent(HttpServletRequest request,
            HttpServletResponse response)
    {
        ModelAndView modelAndView = new ModelAndView();
        List<Student> stuList = stuService.findAll();
        modelAndView.addObject("stuList", stuList);
        modelAndView.setViewName("allStudent");
        return modelAndView;
    }
    
    /**
     * 修改
     */
    @RequestMapping("/pre4Update")
    public ModelAndView update(HttpServletRequest request,
            HttpServletResponse response, Student stu)
    {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("stu", stu);
        modelAndView.setViewName("updateStudent");
        return modelAndView;
    }
    @RequestMapping("/updateStudent")
    public String updateStudent(HttpServletRequest request, HttpServletResponse response, Student stu)
    {
        this.stuService.update(stu);
        return "redirect:/student/allStudent.do";
    }
    
    /**
     * 用于跳转
     */
    @RequestMapping("redir/{url}")
    public String redir(HttpServletRequest request,
            HttpServletResponse response, @PathVariable("url")
            String url)
    {
        return url;
    }
}

===============================配置文件=============================================
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<configuration>
	<mappers>
		<mapper resource="demo/mapper/StudentInfoMapper.xml" />
	</mappers>
</configuration>

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" " http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
	<bean id="stuDao" class="demo.dao.impl.StudentDaoImpl"></bean>
<bean id="stuService" class="demo.service.impl.StudentServiceImpl">
		<property name="stuDao" ref="stuDao" />
	</bean>
</beans>

spring核心配置文件:servlet.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">



	
	<context:component-scan base-package="demo.controller"></context:component-scan>

	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>


	<!-- 数据库连接配置文件路径及读取方式 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</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>

	<!-- 配置mybatis固定的写法 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="configLocation" value="/WEB-INF/classes/ibatis/SqlMapConfig.xml"/>
	</bean>
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
	</bean>
	
</beans>


jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/demo?characterEncoding=gb2312
jdbc.username=root
jdbc.password=root


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">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>demo2</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/classes/spring/*.xml</param-value>
		</init-param>

		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>demo2</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	<!-- 添加过滤器 -->
	<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>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

============================jsp=========================================
allStudent.jsp
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="e"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>Student 列表</title>
		<script type="text/javascript">
			function update(event)
			{
				alert(event.srcElement.parentNode.previousSibling.childNodes[0].nodeValue);
				document.myForm.elements[0].value = event.srcElement.parentNode.previousSibling.previousSibling.previousSibling.previousSibling.childNodes[0].nodeValue;
				document.myForm.elements[1].value = event.srcElement.parentNode.previousSibling.previousSibling.previousSibling.childNodes[0].nodeValue;
				document.myForm.elements[2].value = event.srcElement.parentNode.previousSibling.previousSibling.childNodes[0].nodeValue;
				document.myForm.elements[3].value = event.srcElement.parentNode.previousSibling.childNodes[0].nodeValue;
				document.myForm.submit();
			}
		</script>
	</head>
	<body>
		<table width="50%" border="1">
			<tr>
				<td>
					id
				</td>
				<td>
					姓名
				</td>
				<td>
					性别
				</td>
				<td>
					地址
				</td>
				<td>
					操作
				</td>
			</tr>
			<e:forEach items="${requestScope.stuList}" var="stu">
				<tr>
					<td>
						${stu.id}
					</td>
					<td>
						${stu.name}
					</td>
					<td>
						${stu.sex}
					</td>
					<td>
						${stu.address}
					</td>
					<td>
						<a onclick="javascript:update(event)" href="javascript:void(0)">修改</a>||
						<a href="delete/${stu.id}.do"> 删除</a>
					</td>
				</tr>
			</e:forEach>
		</table>
		<a href="redir/addStudent.do">添加</a>
		<form name="myForm" action="pre4Update.do" method="post">
			<input type="hidden" name="id" />
			<input type="hidden" name="name" />
			<input type="hidden" name="sex" />
			<input type="hidden" name="address" />
		</form>
	</body>
</html>

你可能感兴趣的:(springMVC)