SpringMVC+Mybatis整合的增删改查


本文基于 SPRING注解。本文使用Oracle数据库。

项目文件下载地址:http://download.csdn.net/detail/u010634066/8188965

项目总图:

      


现在lib中导入所有所需jar包:这里就不叙述了

一:在SRC下创建一个Bean包;在bean下面添加实体类,实体类对应于数据表,其属性与数据表相同或多于数据表。

/**
 * 
 */
package com.szz.bean;

import com.szz.base.bean.BaseObject;


 
/**
 * @author Administrator
 *
 */
public class User extends BaseObject {
		
	private String ID;
	/**
	 * @return the iD
	 */
	public String getID() {
		return ID;
	}
	/**
	 * @param iD the iD to set
	 */
	public void setID(String iD) {
		ID = iD;
	}
	/**
	 * @return the nAME
	 */
	public String getNAME() {
		return NAME;
	}
	/**
	 * @param nAME the nAME to set
	 */
	public void setNAME(String nAME) {
		NAME = nAME;
	}
	/**
	 * @return the pASSWORD
	 */
	public String getPASSWORD() {
		return PASSWORD;
	}
	/**
	 * @param pASSWORD the pASSWORD to set
	 */
	public void setPASSWORD(String pASSWORD) {
		PASSWORD = pASSWORD;
	}
	private String NAME;
	private String PASSWORD;
	/* (non-Javadoc)
	 * @see com.szz.base.bean.BaseObject#toString()
	 */
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "User [ID=" + ID + ", NAME=" + NAME + ", PASSWORD=" + PASSWORD
				+ "]";

 }
	
}

二、创建com.szz.dao包;里面用来定义需要对数据进行操作的实体类型DAO接口


/**
 * 
 */
package com.szz.dao;

import java.util.List;

import com.szz.bean.User;

/**
 * @author Administrator
 *
 */
public interface UserDao {

	/*
	 * 查询
	 */
	public List<User> selectAll();

	public User findById(String id);
	
	public User findByUserName(String userName);
	
	public int countAll();
	
	/*
	 * 更新删除插入
	 */
	public int insert(User user);
	
	public int update(User user);
	
	public int delete(String userName);
	
/*	//返回插入数据的ID
	public int findInsertUserID(User user);*/
	
	/*//批处理   插入多条数据
	public void insertUsers(List<User> users);*/
	
}

三、创建包com.szz.tables.xml(这样命名好像不好  定义com.szz.Mappers比较直观一点)   这个是用来写sql语句的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.szz.dao.UserDao">
 	<select id="selectAll" resultType="User">
 		select * from SM_USER 
 	</select>
 	
 	<select id="countAll">
 		select count(*) c from SM_USER 
 	</select>
 	
 	<select id="findById" parameterType="String" resultType="User">
 		select * from SM_USER where ID=#{ID}
 	</select>
 	
 	<select id="findByUserName" parameterType="String" resultType="User">
 		select * from SM_USER where NAME=#{NAME}
 	</select>
 	
 	
 	<!-- <select id="findInsertUserID" paramterType="Srtring">
 		select ID FROM SM_USER NAME =#{User.NAME}
 	</select> -->
 	<insert id="insert" parameterType="User">
 		insert into SM_USER(ID,NAME,PASSWORD) VALUES(#{ID},#{NAME},#{PASSWORD})
 	</insert>
 	
 	
 	<update id="update" parameterType="User">
		update SM_USER 
		<set>
		<!-- 这里要注意后面的    逗号“,”  因为有多个参数需要用逗号隔开  否则会报错 -->
			<if test="NAME!=null">NAME=#{NAME},</if>
			<if test="PASSWORD!=null">PASSWORD=#{PASSWORD}</if>
		</set>
			where ID=#{ID}
 	</update>
 	
 	<delete id="delete" parameterType="String">
 		delete FROM SM_USER WHERE ID=#{ID}
 	</delete>
 </mapper>

命名空间定义为我们需要对应的DAO接口;这里每个方法的ID都跟DAO里面的方法一一对应;

还有说明一下

parameterType="User"
如果你没有在mybatis配置文件里面定义别名  这样写就会报错   你要把全类名写清楚

 <typeAliases>
    	<typeAlias type="com.szz.bean.User" alias="User"/>
    </typeAliases> 



四、spring的配置文件  spring-context.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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:jee="http://www.springframework.org/schema/jee"
       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.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
           http://www.springframework.org/schema/jee
           http://www.springframework.org/schema/jee/spring-jee.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd">

    
    
      <!-- 启动扫描szz下所有的注解--> 
	<context:component-scan base-package="com.szz"/>
	
	<mvc:annotation-driven ignore-default-model-on-redirect="true"/> 

	<mvc:default-servlet-handler/>
    <!-- 可通过注解控制事务
    <tx:annotation-driven />   -->  
    
    <!-- 导入外部的资源文件   一般都会把数据源的配置文件房子properties文件里面  然后用这种方式来导入  
	<context:property-placeholder location="classpath:jdbc.properties"/>-->
	
       <!--   
    配置DataSource数据源   配置mysql方式
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <property name="maxActive" value="5" />
        <property name="maxIdle" value="3" />
        <property name="maxWait" value="1000" />
        <property name="defaultAutoCommit" value="true" />
        <property name="removeAbandoned" value="true" />
        <property name="removeAbandonedTimeout" value="60" />
    </bean>  -->

    <!-- 配置DataSource数据源    oracle方式-->
 
    
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        		 
                <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:myoracle" />
                
                <property name="username" value="SRC" />
                <property name="password" value="src123456" />
                

    </bean> 
    
    
    
    
    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx 
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  -->  
    
     
<!-- 创建SqlSessionFactory,同时指定数据源 

 <span id="blogcontent" style="font-family:tahoma, arial, 宋体, sans-serif;line-height: 24px; background-color: #ffffff;">SqlSession也是由SqlSessionFactory来产生的,但是Mybatis-Spring给我们封装了一个SqlSessionFactoryBean,
在这个bean里面还是通过SqlSessionFactoryBuilder来建立对应的SqlSessionFactory,进而获取到对应的SqlSession。
通过SqlSessionFactoryBean我们可以通过对其指定一些属性来提供Mybatis的一些配置信息。
所以接下来我们需要在Spring的applicationContext配置文件中定义一个SqlSessionFactoryBean。</span>
  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        
        <property name="mapperLocations"  

             value="classpath:com/szz/tables/xml/*.xml" /> 
             
         <property name="configLocation" value="classpath:mybatis-config.xml"></property>  
    </bean> 
    
    
    
    
     <!-- jsp页面解析器,当Controller返回XXX字符串时,先通过拦截器,然后该类就会在/WEB-INF/views/目录下,查找XXX.jsp文件-->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
	
	
    
 <!--  
    Mapper接口所在包名,Spring会自动查找其下的Mapper  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.szz.dao" />  
    </bean>  
     -->
    
    <!-- ,MapperFactoryBean会从它的getObject方法中获取对应的Mapper接口,
    而getObject内部还是通过我们注入的属性调用
    SqlSession接口的getMapper(Mapper接口)方法来返回对应的Mapper接口的 -->
    
   <!-- 用户Dao -->
	<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">  
    	<property name="mapperInterface" value="com.szz.dao.UserDao" />  
    	<property name="sqlSessionFactory" ref="sqlSessionFactory" />  
	</bean>
    
    
    
</beans>
    

配置文件说明:  详情见http://www.blogjava.net/ldwblog/archive/2013/07/10/401418.html


在定义SqlSessionFactoryBean的时候,dataSource属性是必须指定的,它表示用于连接数据库的数据源。当然,我们也可以指定一些其他的属性,下面简单列举几个:

  • mapperLocations:它表示我们的Mapper文件存放的位置,当我们的Mapper文件跟对应的Mapper接口处于同一位置的时候可以不用指定该属性的值。

  • configLocation:用于指定Mybatis的配置文件位置。如果指定了该属性,那么会以该配置文件的内容作为配置信息构建对应的SqlSessionFactoryBuilder,但是后续属性指定的内容会覆盖该配置文件里面指定的对应内容。

  • typeAliasesPackage:它一般对应我们的实体类所在的包,这个时候会自动取对应包中不包括包名的简单类名作为包括包名的别名。多个package之间可以用逗号或者分号等来进行分隔。

  • typeAliases:数组类型,用来指定别名的。指定了这个属性后,Mybatis会把这个类型的短名称作为这个类型的别名,前提是该类上没有标注@Alias注解,否则将使用该注解对应的值作为此种类型的别名。

    • plugins:数组类型,用来指定Mybatis的Interceptor。

    • typeHandlersPackage:用来指定TypeHandler所在的包,如果指定了该属性,SqlSessionFactoryBean会自动把该包下面的类注册为对应的TypeHandler。多个package之间可以用逗号或者分号等来进行分隔。

    • typeHandlers:数组类型,表示TypeHandler


    •  接下来就是在Spring的applicationContext文件中定义我们想要的Mapper对象对应的MapperFactoryBean了。通过MapperFactoryBean可以获取到我们想要的Mapper对象。MapperFactoryBean实现了Spring的FactoryBean接口,所以MapperFactoryBean是通过FactoryBean接口中定义的getObject方法来获取对应的Mapper对象的。在定义一个MapperFactoryBean的时候有两个属性需要我们注入,一个是Mybatis-Spring用来生成实现了SqlSession接口的SqlSessionTemplate对象的sqlSessionFactory;另一个就是我们所要返回的对应的Mapper接口了。

          定义好相应Mapper接口对应的MapperFactoryBean之后,我们就可以把我们对应的Mapper接口注入到由Spring管理的bean对象中了,比如Service bean对象。这样当我们需要使用到相应的Mapper接口时,MapperFactoryBean会从它的getObject方法中获取对应的Mapper接口,而getObject内部还是通过我们注入的属性调用SqlSession接口的getMapper(Mapper接口)方法来返回对应的Mapper接口的。这样就通过把SqlSessionFactory和相应的Mapper接口交给Spring管理实现了Mybatis跟Spring的整合。

    对应xml
  •  <!-- 用户Dao -->
    	<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">  
        	<property name="mapperInterface" value="com.szz.dao.UserDao" />  
        	<property name="sqlSessionFactory" ref="sqlSessionFactory" />  
    	</bean>



MapperScannerConfigurer

      利用上面的方法进行整合的时候,我们有一个Mapper就需要定义一个对应的MapperFactoryBean,当我们的Mapper比较少的时候,这样做也还可以,但是当我们的Mapper相当多时我们再这样定义一个个Mapper对应的MapperFactoryBean就显得速度比较慢了。为此Mybatis-Spring为我们提供了一个叫做MapperScannerConfigurer的类,通过这个类Mybatis-Spring会自动为我们注册Mapper对应的MapperFactoryBean对象。

      如果我们需要使用MapperScannerConfigurer来帮我们自动扫描和注册Mapper接口的话我们需要在Spring的applicationContext配置文件中定义一个MapperScannerConfigurer对应的bean。对于MapperScannerConfigurer而言有一个属性是我们必须指定的,那就是basePackage。basePackage是用来指定Mapper接口文件所在的基包的,在这个基包或其所有子包下面的Mapper接口都将被搜索到。多个基包之间可以使用逗号或者分号进行分隔。最简单的MapperScannerConfigurer定义就是只指定一个basePackage属性,如:

Xml代码  
  1. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  

  2.   <property name="basePackage" value="com.tiantian.mybatis.mapper" />  

  3. bean>  


      这样MapperScannerConfigurer就会扫描指定基包下面的所有接口,并把它们注册为一个个MapperFactoryBean对象。



五、创建mybatis-config.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
"http://mybatis.org/dtd/mybatis-3-config.dtd">  
<configuration>
	


<!-- 	<environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:LEARN" />
                <property name="username" value="system" />
                <property name="password" value="src123456" />
            </dataSource>
        </environment>
    </environments> -->
<!--别名定义-->
 <typeAliases>
    	<typeAlias type="com.szz.bean.User" alias="User"/>
    </typeAliases> 

 
 

	<!-- 映射文件,存放sql语句的配置文件 -->
	<!-- <mappers>
		<mapper resource="com/szz/tables/xml/UserDaoMapper.xml" />
	</mappers> -->
</configuration>

六、创建services接口

package com.szz.service;

import java.util.List;

import com.szz.bean.User;

public interface UserService {

	public List<User> getUsers();
	
	/*
	 * 濡傛灉ID涓虹┖灏辨壘username    濡傛灉username涓虹┖灏辨壘ID锛�閮藉~鎸夌収ID
	 */
	public User getUserInfo(String ID,String userName);
	
	public int getCount();
	
	
//	public int saveUser(User user);
	
	public int insertUser(User user);
	public int updateUser(User user);
	
	public int deleteUser(String ID);
}

七‘services接口的实现类  serviceImpl


/**
 * 
 */
package com.szz.service.impl;

import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.szz.bean.User;
import com.szz.dao.UserDao;
import com.szz.service.UserService;

/**
 * @author Administrator
 *
 */
@Service("userService")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	/*
	@Autowired
	private SqlSessionTemplate sessionTemplate;*/
	

	public UserDao getUserDao() {
		return userDao;
	}

	/**
	 * @param userDao the userDao to set
	 */
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public List<User> getUsers() {
		// TODO Auto-generated method stub
		return userDao.selectAll();
		//return sessionTemplate.getMapper(UserDao.class).selectAll();
	}

	@Override
	public User getUserInfo(String ID, String userName) {
		// TODO Auto-generated method stub
		if(ID!=null){
			return userDao.findById(ID);
		}
		else
			return userDao.findByUserName(userName);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return userDao.countAll();
	}

	@Override
	public int insertUser(User user) {
		// TODO Auto-generated method stub
			return userDao.insert(user);
	}
	
	@Override
	public int updateUser(User user) {
		// TODO Auto-generated method stub
			return userDao.update(user);
	}

	@Override
	public int deleteUser(String ID) {
		// TODO Auto-generated method stub
		return userDao.delete(ID);
	}
	
	
}

八、创建控制类controller包/**
/**
 * 
 */
package com.szz.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;


import com.szz.base.acion.BaseAction;
import com.szz.bean.User;
import com.szz.service.UserService;

/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value="/user")
public class UserAction extends BaseAction {
	@Autowired
	private UserService userService;
	
	
	
    @RequestMapping(value="/login",method=RequestMethod.POST)
		public String login(){ 
    	
			return "redirect:/user/userList";
		}
	 
    @RequestMapping(value="userList")
    public ModelAndView showAll(){
    	System.out.println("index......");
    	ModelAndView MV = new ModelAndView("user/index");
    	List<User> userList = new ArrayList<User>();
    	userList = userService.getUsers();
    	MV.addObject("userList",userList);
    	return MV;
    }
	@RequestMapping(value="/add")
	public ModelAndView login(HttpServletRequest request,@RequestParam(value="username", required=true, defaultValue="szz") String name){ 
		System.out.println("/user/login....");
		ModelAndView mv = new ModelAndView("user/success");  
	    mv.addObject("add", "娣诲姞"); 
	    return mv;  
	}
	@RequestMapping(value="/edituser")
	public ModelAndView edit(@RequestParam(value="ID") String ID){
		ModelAndView mv = new ModelAndView("user/edit");
		User user = userService.getUserInfo(ID, null);
		mv.addObject("user",user);
		return mv;
	}
	
	@RequestMapping(value="/deleteuser")
	public String deleteuser(@RequestParam(value="ID") String ID){
		userService.deleteUser(ID);
		return "redirect:/user/userList";
	}
	@RequestMapping(value="/userset",method=RequestMethod.POST)  
	public String user(@ModelAttribute("user")User user ) {
		 System.out.println(user.getNAME());
		 return "user/success";   
	}
	
	@RequestMapping(value="/insertuser",method=RequestMethod.POST)  
	public String insertUser( User userInfo ) throws Exception {  
		userService.insertUser(userInfo);
		return "redirect:/user/userList";
	}
	
	@RequestMapping(value="/updateuser",method=RequestMethod.POST)  
	public String updateUser( User userInfo ) throws Exception {  
		userService.updateUser(userInfo);
		return "redirect:/user/userList";
	}
	
}


九、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">
	
	
	 <servlet>
    	<servlet-name>Dispatcher</servlet-name>
    	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    	<init-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>
    			classpath*:spring-context.xml
    		</param-value>
    	</init-param>
    	<load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>


十、一些页面之类的;

index.jsp

 <body>
  
   
   <form action="/SpringMvcMybatisFreeMarker/user/login" method="post">
   		用户ID:<input  type="text" name="id" value=""/>
   		<br>用户名称:<input  type="text" id="username" name="username" value=""/>
   		<br>用户密码:<input  type="text" name="password" value=""/>
   		<br><input type="submit" value="提交" />
   </form>
  </body>

user/index.jsp

<body>

  
  	<form action="user/insertuser"  method="post">
  	<table>
  	
  			<tr>
  			 
  			<th>ID</th>
  			<td><input type="text"  name="ID" /> </td>
  		</tr>
  		<tr>
  		<tr>
  			 
  			<th>账号</th>
  			<td><input type="text"  name="NAME" /> </td>
  		</tr>
  		<tr>
  			 
  			<th>密码</th>
  			<td><input type="text"  name="PASSWORD" /></td>
  		</tr>
  		<tr>
  			<td colspan="2"><input type="submit" value="添加"> </td>
  		</tr>
  	</table>
  	</form>
  	
  	<table>
  		<tr>
  			<th>id</th>
  			<th>账号</th>
  			<th>密码</th>
  			<th>功能</th>
  		</tr>
  		 
  		<c:forEach items="${userList}"  var="user">
     	<tr>
  			<td>${user.ID}</td>
  			<td>${user.NAME}</td>
  			<td>${user.PASSWORD}</td>
  			<td><a href="user/edituser?ID=${user.ID}">修改</a>   <a href="user/deleteuser?ID=${user.ID}">删除</a> </td>
  		</tr>
     </c:forEach>
  	</table>
    
  </body>
</html>

user/edit.jsp

<body>
  	<form action="user/updateuser"  method="post">
  	<input type="text" name="ID" value="${user.ID}" />
  	<table>
  		<tr> 
  			<th>账号</th>
  			<td><input type="text" name="NAME" value="${user.NAME}" /></td>
  		</tr>
  		<tr>
  			 
  			<th>密码</th>
  			<td><input type="text" name="PASSWORD" value="${user.PASSWORD}" /></td>
  		</tr>
  		<tr>
  			<td colspan="2"><input type="submit" value="修改"> </td>
  		</tr>
  	</table>
  	</form> 
    
  </body>


访问:http://localhost:8080/SpringMvcMybatisFreeMarker/index.jsp

猜你喜欢

转载自blog.csdn.net/u010634066/article/details/41409011