前面给大家讲了整合的思路和整合的过程,在这里就不在提了,直接把springMVC+spring+Mybatis整合的实例代码(单表的增删改查)贴给大家:
首先是目录结构:
仔细看看这个目录结构:我不详细解释了直接把所有的代码贴出来
实体类:com.etc.entity.User.java(get,set,空的构造方法,tostring记得生成)
public class User implements Serializable{ private static final long serialVersionUID = 1L; private int userid; private String uname; private String upassword; private String usex; }
dao:com.ect.dao(这个里面因为包扫描的规则必须把mapper的接口和mapper的xml放在同一个包底下,并且名称一样,在idea中如果无法使用,可以加上@Repository这个注解)
com.etc.dao.UserMapper.java(里面是增删改查的接口)
public interface UserMapper { public List<User> findAll(); public void insertUser(User user); public void deleteUserById(int userid); public User findById(int userid); public void updateUser(User user); }
com.etc.dao.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"> <!-- 命名空间,可以对sql进行分类的一个管理 --> <mapper namespace="com.etc.dao.UserMapper"> <!-- 查询全部 --> <select id="findAll" resultType="com.etc.entity.User"> select * from t_user; </select> <!-- 根据ID查询--> <select id="findById" parameterType="int" resultType="com.etc.entity.User"> select * from t_user where userid=#{userid}; </select> <!-- 插入--> <insert id="insertUser" parameterType="User"> insert into t_user (uname,upassword,usex)values(#{uname},#{upassword},#{usex}); </insert> <!-- 删除--> <delete id="deleteUserById" parameterType="int"> delete from t_user where userid=#{userid} </delete> <!-- 更新--> <update id="updateUser" parameterType="User"> update t_user set uname=#{uname},upassword=#{upassword},usex=#{usex} where userid=#{userid} </update> </mapper>
业务类接口:com.etc.service.UserService.java
public interface UserService { List<User>findAll(); public void insertUser(User user); public void deleteUserById(int userid); public User findById(int userid); public void updateUser(User user); }
业务类的实现类:com.etc.srvice.impl.UserServiceImpl.java
这里有几个注意的地方:
1.需要用@Service这个注解标识者是一个业务类
2.需要用@Autowired或者@Resource把mapper的接口对象注入到spring中(就是如下加个注解就好)
3.这是使用的是非注解的事物配置
@Service public class UserServiceImpl implements UserService{ @Autowired private UserMapper userMapper;//mapper的接口 public List<User> findAll() { // TODO Auto-generated method stub return userMapper.findAll(); } public void insertUser(User user) { userMapper.insertUser(user); } public void deleteUserById(int userid) { // TODO Auto-generated method stub userMapper.deleteUserById(userid); } public User findById(int userid) { // TODO Auto-generated method stub return userMapper.findById(userid); } public void updateUser(User user) { // TODO Auto-generated method stub userMapper.updateUser(user); } }
控制器:com.etc.controller.UserController.java
这里也有几个地方需要注意:
1.需要用这个注解标识这是一个控制器
2.需要用@Autowired或者@Resource把service的接口对象注入到spring中(就是如下加个注解就好)
@Controller public class UserController { @Resource private UserService ueService; /** * 跳转到添加的页面 * @return */ @RequestMapping(value="/insert") public String insert(){ return "insert"; } /** * 添加用户 * @param user * @return */ @RequestMapping(value="/insertUser") public String insertUser(User user){ ueService.insertUser(user); return "redirect:findAll"; } /** * 根据ID删除用户 * @param user * @return */ @RequestMapping(value="/deleteUserById") public String deleteUserById(int userid){ ueService.deleteUserById(userid); return "redirect:findAll"; } /** * 根据ID查找用户 * @param user * @return */ @RequestMapping(value="/findById") public String findById(Model model,int userid){ User user=ueService.findById(userid); model.addAttribute("user", user); return "update"; } /** * 更新用户 * @param user * @return */ @RequestMapping(value="/updateUser") public String updateUser(User user){ ueService.updateUser(user); return "redirect:findAll"; } /** * 查找所有用户 * @return */ @RequestMapping(value="/findAll") public ModelAndView findAll(){ ModelAndView mv= new ModelAndView(); List<User>list=ueService.findAll(); mv.addObject("list",list); mv.setViewName("listuser"); return mv; } }
Mybatis的全局配置文件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> <typeAliases> <typeAlias type="com.etc.entity.User" alias="User" /> </typeAliases> </configuration>
spring的配置文件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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 配置数据源的文件的位置 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 配置数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 数据库连接池 --> </bean> <!-- 配置SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定数据源 --> <property name="dataSource" ref="dataSource"></property> <!-- 指定Mybatis配置文件的路径 --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property> </bean> <!-- 配置mapper的扫描包 --> <!-- 去bean的时候,的规则:bean的名字=原先类的类名小写 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.etc.dao"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- 事物的配置 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 数据源 --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 通知 --> <tx:advice transaction-manager="transactionManager" id="txAdvice"> <!-- 传播行为:什么方法需要用到事物 --> <tx:attributes> <!--<tx:method name="*" rollback-for="RunTimeException"/>--> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> <tx:method name="select*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- Aop 告诉spring哪里需要用到事物--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.etc.service.impl.*.*(..))"/> </aop:config> </beans>
springMVC的配置文件dispatcher-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:p="http://www.springframework.org/schema/p" 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-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"> <!-- 默认的注解映射支持 --> <mvc:annotation-driven/> <!-- 启用自动扫描 --> <context:component-scan base-package="com.etc.*"></context:component-scan> <!-- 配置ViewResolver --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
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"> <!-- spring 容器配置 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- spring 配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring/applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>dispatch</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 默认的配置文件的地址:/WEB-INF/servlet的名字-servlet.xml <init-param>--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/dispatcher-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatch</servlet-name> <!-- 第一种:*.html,*.action 就是过滤以.xxx结尾的 第二种:/ 所有的地址都会进入这个进行解析,静态的资源,需要添加配置 第三种:/* 他就是变态,连jsp页面都进来,结果就是报错XXXXX别用 --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- post中文乱码处理 --> <filter> <filter-name>CharacterEncodingFilter</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> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
到这里代码就结束了,页面就不给了,自己写看着写吧。
总结一下过程:
这里只要记得流程是这样的:
页面发起一个请求-->控制器-->控制器通过一个service对象调用service的方法-->service中通过userMapper对象调用dao中的方法-->去查询数据库