在Maven使用SSM框架实现对数据库进行增删改查操作?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
Spring介绍:
spring 使用基本的 JavaBean 来完成以前只可能由 EJB 完成的事情。然而, Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java 应用都可以从 Spring 中受益。 简单来说, Spring 是一个轻量级的控制反转(IoC )和面向切面( AOP )的容器框架。
SpringMVC介绍
Spring MVC 属于 SpringFrameWork 的后续产品,已经融合在Spring Web Flow 里面。 Spring MVC 分离了 控制器 、模型 对象 、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
MyBatis介绍
MyBatis 本是 apache 的一个开源项目 iBatis , 2010 年这个项目由apache software foundation 迁移到了 google code ,并且改名为 MyBatis 。MyBatis 是一个基于 Java 的 持久层 框架。 iBATIS 提供的 持久层 框架包括SQL Maps 和 Data Access Objects ( DAO ) MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索。 MyBatis 使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs ( Plain Old Java Objects ,普通的 Java 对象)映射成数据库中的记录。
首先不是maven架构整合的 SSM 框架
创建数据库、表db_zsl t_user user_t【最下面有sql语句】
1.项目整体结构
2.添加相关jar 包
3.项目整体结构出来了
4.创建model【User】
package comlytmodel; /** * 用户 * @author * */ public class User { private int id; private String userName; private String age; @Override public String toString() { return "User [id=" + id + ", age=" + age + ", userName=" + userName + "]"; } public User(){ super(); } public int getId() { return id; } public void setId(int id) { thisid = id; } public String getAge() { return age; } public void setAge(String age) { thisage = age; } public String getUserName() { return userName; } public void setUserName(String userName) { thisuserName = userName; } public User(int id, String age, String userName) { super(); thisid = id; thisage = age; thisuserName = userName; } }
5.创建DAO接口【在mybatis中 mapper就相当于dao】
package comlytmapper; import javautilList; import comlytmodelUser; /** * 做为 DAO的接口 * @author */ public interface UserMapper { void save(User user); boolean update(User user); boolean delete(int id); User findById(int id); List<User> findAll(); }
6.实现dao接口【mybatis中就是UserMapper.xml文件】
<?xml version="0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatisorg//DTD Mapper 0//EN" "http://mybatisorg/dtd/mybatis-3-mapperdtd"> <!-- namespace:必须与对应的接口全类名一致 UserMapperjava id :必须与对应接口的某个对应的方法名一致即必须要和UserMapperjava接口中的方法同名。 --> <mapper namespace="comlytmapperUserMapper"> <insert id="save" parameterType="User"> insert into t_user(user_name,user_age) values(#{userName},#{age}) </insert> <update id="update" parameterType="User"> update t_user set user_name=#{userName},user_age=#{age} where user_id=#{id} </update> <delete id="delete" parameterType="int"> delete from t_user where user_id=#{id} </delete> <!-- mybsits_config中配置的alias类别名,也可直接配置resultType为类路径 --> <select id="findById" parameterType="int" resultType="User"> select user_id id,user_name userName,user_age age from t_user where user_id=#{id} </select> <select id="findAll" resultType="User"> select user_id id,user_name userName,user_age age from t_user </select> </mapper>
这里对这个xml文件作几点说明:
1、namespace必须与对应的接口全类名一致。
2、id必须与对应接口的某个对应的方法名一致即必须要和UserMapper.java接口中的方法同名。
7.mybatis与Spring整合【spring-common.xml】放在src的根目录下
对于Mybatis和Spring的整合是这篇博文的重点,需要配置的内容在下面有详细的解释。
<?xml version="0" encoding="UTF-8"?> <beans xmlns="http://wwwspringframeworkorg/schema/beans" xmlns:xsi="http://wwwworg/2001/XMLSchema-instance" xmlns:p="http://wwwspringframeworkorg/schema/p" xmlns:context="http://wwwspringframeworkorg/schema/context" xmlns:tx="http://wwwspringframeworkorg/schema/tx" xsi:schemaLocation=" http://wwwspringframeworkorg/schema/beans http://wwwspringframeworkorg/schema/beans/spring-beans-xsd http://wwwspringframeworkorg/schema/context http://wwwspringframeworkorg/schema/context/spring-context-xsd http://wwwspringframeworkorg/schema/tx http://wwwspringframeworkorg/schema/tx/spring-tx-xsd"> <!-- Mybatis和Spring的整合 --> <!-- 数据源 : DriverManagerDataSource --> <bean id="dataSource" class="orgspringframeworkjdbcdatasourceDriverManagerDataSource"> <property name="driverClassName" value="commysqljdbcDriver" /> <property name="url" value="jdbc:mysql://localhost:3306/db_zsl" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!-- mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源 MyBatis定义数据源,同意加载配置 --> <bean id="sqlSessionFactory" class="orgmybatisspringSqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:mybatis-configxml" /> </bean> <!-- mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory basePackage:指定sql映射文件/接口所在的包(自动扫描) --> <bean class="orgmybatisspringmapperMapperScannerConfigurer"> <property name="basePackage" value="comlytmapper"></property> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> <!-- 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源 --> <bean id="txManager" class="orgspringframeworkjdbcdatasourceDataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 使用声明式事务 transaction-manager:引用上面定义的事务管理器 --> <tx:annotation-driven transaction-manager="txManager" /> </beans>
8.mybatis配置文件【mybatis-config.xml】放在src目录下
<?xml version="0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatisorg//DTD Config 0//EN" "http://mybatisorg/dtd/mybatis-3-configdtd"> <configuration> <!-- 实体类,简称 -设置别名 --> <typeAliases> <typeAlias alias="User" type="comlytmodelUser" /> </typeAliases> <!-- 实体接口映射资源 --> <!-- 说明:如果xxMapperxml配置文件放在和xxMapperjava统一目录下,mappers也可以省略,因为orgmybatisspringmapperMapperFactoryBean默认会去查找与xxMapperjava相同目录和名称的xxMapperxml --> <mappers> <mapper resource="com/lyt/mapper/userMapperxml" /> </mappers> </configuration>
配置log4j.properties
### set log levels ### log4jrootLogger = info , Console , D #Console log4jappenderConsole=orgapachelog4jConsoleAppender log4jappenderConsolelayout=orgapachelog4jPatternLayout log4jappenderConsolelayoutConversionPattern=%d [%t] %-5p [%c] - %m%n log4jloggerjavasqlResultSet=INFO log4jloggerorgapache=INFO log4jloggerjavasqlConnection=INFO log4jloggerjavasqlStatement=INFO log4jloggerjavasqlPreparedStatement=INFO #output2file log4jappenderD = orgapachelog4jDailyRollingFileAppender log4jappenderDFile = D\:/logs/loglog log4jappenderDAppend = true log4jappenderDThreshold = INFO \#\# \u00E8\u00BE\u0093\u00E5\u0087\u00BAinfo\u00E7\u00BA\u00A7\u00E5\u0088\u00AB\u00E4\u00BB\u00A5\u00E4\u00B8\u008A\u00E7\u009A\u0084\u00E6\u0097\u00A5\u00E5\u00BF\u0097 log4jappenderDlayout = orgapachelog4jPatternLayout log4jappenderDlayoutConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [ %t\:%r ] - [ %p ] %m%n
10.整合Springmvc
配置【spring-mvc.xml】放在src根目录下
<?xml version="0" encoding="UTF-8"?> <beans xmlns="http://wwwspringframeworkorg/schema/beans" xmlns:xsi="http://wwwworg/2001/XMLSchema-instance" xmlns:context="http://wwwspringframeworkorg/schema/context" xmlns:mvc="http://wwwspringframeworkorg/schema/mvc" xsi:schemaLocation="http://wwwspringframeworkorg/schema/beans http://wwwspringframeworkorg/schema/beans/spring-beansxsd http://wwwspringframeworkorg/schema/context http://wwwspringframeworkorg/schema/context/spring-context-xsd http://wwwspringframeworkorg/schema/mvc http://wwwspringframeworkorg/schema/mvc/spring-mvc-xsd"> <!-- 注解扫描包 --> <context:component-scan base-package="comlytcontroller" /> <context:component-scan base-package="comlytservice" /> <!-- 开启注解 --> <mvc:annotation-driven /> <!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,04新增功能,需要重新设置spring-mvc-xsd --> <mvc:resources mapping="/img/**" location="/img/" /> <mvc:resources mapping="/js/**" location="/js/" /> <mvc:resources mapping="/css/**" location="/css/" /> <mvc:resources mapping="/html/**" location="/html/" /> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean id="viewResolver" class="orgspringframeworkwebservletviewInternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value="jsp" /> </bean> </beans>
11.配置web.xml
<?xml version="0" encoding="UTF-8"?> <web-app version="5" xmlns="http://javasuncom/xml/ns/javaee" xmlns:xsi="http://wwwworg/2001/XMLSchema-instance" xsi:schemaLocation="http://javasuncom/xml/ns/javaee http://javasuncom/xml/ns/javaee/web-app_2_xsd"> <!-- 加载Spring容器配置 --> <listener> <listener-class>orgspringframeworkwebcontextContextLoaderListener</listener-class> </listener> <!-- 设置Spring容器加载所有的配置文件的路径 --> <context-param> <param-name>contextConfigLocation</param-name> <!-- <param-value>classpath:config/spring-*xml</param-value> --> <param-value>classpath:spring-commonxml,classpath:spring-mvcxml</param-value> </context-param> <!-- 配置SpringMVC核心控制器 --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>orgspringframeworkwebservletDispatcherServlet</servlet-class> <!-- 配置初始配置化文件,前面contextConfigLocation看情况二选一 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-commonxml,classpath:spring-mvcxml</param-value> </init-param> <!-- 启动加载一次 --> <load-on-startup>1</load-on-startup> </servlet> <!--为DispatcherServlet建立映射 --> <servlet-mapping> <servlet-name>springMVC</servlet-name> <!-- 此处可以可以配置成*do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class>orgspringframeworkwebutilIntrospectorCleanupListener</listener-class> </listener> <!-- 解决工程编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>orgspringframeworkwebfilterCharacterEncodingFilter</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> <welcome-file-list> <welcome-file>indexjsp</welcome-file> </welcome-file-list> </web-app>
12.建立service以及service实现【UserService.java】
package comlytservice; import javautilList; import comlytmodelUser; public interface UserService { void save(User user); boolean update(User user); boolean delete(int id); User findById(int id); List<User> findAll(); }
【UserServiceImpl.java】
package comlytserviceimpl; import javautilList; import javaxannotationResource; import orgspringframeworkstereotypeService; import orgspringframeworktransactionannotationTransactional; import comlytmapperUserMapper; import comlytmodelUser; import comlytserviceUserService; @Service @Transactional // 此处不再进行创建SqlSession和提交事务,都已交由spring去管理了。 public class UserServiceImpl implements UserService { @Resource private UserMapper mapper; /** * 根据 id 删除 数据 */ public boolean delete(int id) { return mapperdelete(id); } /** * 查询User的全部数据 */ public List<User> findAll() { List<User> findAllList = mapperfindAll(); return findAllList; } /** * 根据 id 查询 对应数据 */ public User findById(int id) { User user = mapperfindById(id); return user; } /** * 新增数据 */ public void save(User user) { mappersave(user); } /** * 根据 id 修改对应数据 */ public boolean update(User user) { return mapperupdate(user); } }
13.建立Controller【UserController.java】
package comlytcontroller; import javaioIOException; import javaioPrintWriter; import javautilList; import javaxservlethttpHttpServletRequest; import javaxservlethttpHttpServletResponse; import orgspringframeworkbeansfactoryannotationAutowired; import orgspringframeworkstereotypeController; import orgspringframeworkuiModel; import orgspringframeworkwebbindannotationRequestMapping; import comlytmodelUser; import comlytserviceUserService; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; /** * 获取所有用户列表 * @param request * @return */ @RequestMapping("/getAllUser") public String getAllUser(HttpServletRequest request,Model model){ List<User> user = userServicefindAll(); modeladdAttribute("userList", user); requestsetAttribute("userList", user); return "/allUser"; } /** * 跳转到添加用户界面 * @param request * @return */ @RequestMapping("/toAddUser") public String toAddUser(){ return "/addUser"; } /** * 添加用户并重定向 * @param user * @param request * @return */ @RequestMapping("/addUser") public String addUser(User user,Model model){ userServicesave(user); return "redirect:/user/getAllUser"; } /** *编辑用户 * @param user * @param request * @return */ @RequestMapping("/updateUser") public String updateUser(User user,HttpServletRequest request,Model model){ if(userServiceupdate(user)){ user = userServicefindById(usergetId()); requestsetAttribute("user", user); modeladdAttribute("user", user); return "redirect:/user/getAllUser"; }else{ return "/error"; } } /** * 根据id查询单个用户 * @param id * @param request * @return */ @RequestMapping("/getUser") public String getUser(int id,HttpServletRequest request,Model model){ requestsetAttribute("user", userServicefindById(id)); modeladdAttribute("user", userServicefindById(id)); return "/editUser"; } /** * 删除用户 * @param id * @param request * @param response */ @RequestMapping("/delUser") public void delUser(int id,HttpServletRequest request,HttpServletResponse response){ String result = "{\"result\":\"error\"}"; if(userServicedelete(id)){ result = "{\"result\":\"success\"}"; } responsesetContentType("application/json"); try { PrintWriter out = responsegetWriter(); outwrite(result); } catch (IOException e) { eprintStackTrace(); } } }
至此 大部分架构以及代码已经搭建完成
我们来做前台页面--修改index.jsp
<%@ page language="java" import="javautil*" pageEncoding="utf-8"%> <% String path = requestgetContextPath(); String basePath = requestgetScheme() + "://" + requestgetServerName() + ":" + requestgetServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 01 Transitional//EN"> <html> <head> <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > <title>首页</title> </head> <body> <h6> <a href="<%=basePath%>user/getAllUser" rel="external nofollow" >进入用户管理页</a> </h6> </body> </html>
在 WEB-INF 下新建jsp文件夹【里面新建以下文件】【addUser.jsp】【allUser.jsp】【editUser.jsp】
addUser.jsp内容
<%@ page language="java" import="javautil*" pageEncoding="UTF-8"%> <% String path = requestgetContextPath(); String basePath = requestgetScheme()+"://"+requestgetServerName()+":"+requestgetServerPort()+path+"/"; %> <%@ taglib uri="http://javasuncom/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 01 Transitional//EN"> <html> <head> <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > <title>添加用户</title> <script type="text/javascript"> function addUser(){ var form = documentforms[0]; formaction = "<%=basePath%>user/addUser"; formmethod="post"; formsubmit(); } </script> </head> <body> <h2><%=path%>添加用户<%=basePath%></h2> <form action="" name="userForm"> 姓名:<input type="text" name="userName"> 年龄:<input type="text" name="age"> <input type="button" value="添加" onclick="addUser()"> </form> </body> </html>
allUser.jsp
<%@ page language="java" import="javautil*" pageEncoding="UTF-8"%> <% String path = requestgetContextPath(); String basePath = requestgetScheme()+"://"+requestgetServerName()+":"+requestgetServerPort()+path+"/"; %> <%@ taglib uri="http://javasuncom/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 01 Transitional//EN"> <html> <head> <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > <script type="text/javascript" src="js/jquery-js"></script> <title>用户列表</title> <script type="text/javascript"> function del(id){ $get("<%=basePath%>user/delUser?id=" + id,function(data){ if("success" == dataresult){ alert("删除成功"); windowlocationreload(); }else{ alert("删除失败"); } }); } </script> </head> <body> <h7><a href="<%=basePath%>user/toAddUser" rel="external nofollow" >添加用户</a></h7> <table border="1"> <tbody> <tr> <th>姓名</th> <th>年龄</th> <th>操作</th> </tr> <c:if test="${!empty userList }"> <c:forEach items="${userList}" var="user"> <tr> <td>${useruserName }</td> <td>${userage }</td> <td> <a href="<%=basePath%>user/getUser?id=${userid}" rel="external nofollow" >编辑</a> <a href="javascript:del('${userid }')" rel="external nofollow" >删除</a> </td> </tr> </c:forEach> </c:if> </tbody> </table> </body> </html>
editUser.jsp
<%@ page language="java" import="javautil*" pageEncoding="UTF-8"%> <% String path = requestgetContextPath(); String basePath = requestgetScheme()+"://"+requestgetServerName()+":"+requestgetServerPort()+path+"/"; %> <%@ taglib uri="http://javasuncom/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 01 Transitional//EN"> <html> <head> <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > <title>编辑用户</title> <script type="text/javascript"> function updateUser(){ var form = documentforms[0]; formaction = "<%=basePath%>user/updateUser"; formmethod="post"; formsubmit(); } </script> </head> <body> <h2>添加用户</h2> <form action="" name="userForm"> <input type="hidden" name="id" value="${userid }"/> 姓名:<input type="text" name="userName" value="${useruserName }"/> 年龄:<input type="text" name="age" value="${userage }"/> <input type="button" value="编辑" onclick="updateUser()"/> </form> </body> </html>
到此 简单的整合SSM 【基本的操作内容已经完成】
让你们看下界面运行,地址:http://localhost:8088/SpringMVC_Spring_mybatis/
首页:
点击编辑进去:
点击添加进去:
由于我在网络问题 图片暂时没有上传上去。【现在我把图片都正上去了,希望多多支持】
对应的数据库 表
/* Navicat MySQL Data Transfer Source Server : localhost Source Server Version : 50515 Source Host : localhost:3306 Source Database : db_zsl Target Server Type : MYSQL Target Server Version : 50515 File Encoding : 65001 Date: 2016-05-16 16:10:51 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `t_user` -- ---------------------------- DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(20) NOT NULL, `user_age` varchar(20) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of t_user -- ---------------------------- INSERT INTO `t_user` VALUES ('2', '朱佳鹏', '25'); INSERT INTO `t_user` VALUES ('3', '傻狍子', '150'); INSERT INTO `t_user` VALUES ('4', 'jiuqiyuliang', '23'); INSERT INTO `t_user` VALUES ('5', 'jiuqiyuliang', '23'); INSERT INTO `t_user` VALUES ('6', 'jiuqiyuliang', '23'); INSERT INTO `t_user` VALUES ('7', 'jiuqiyuliang', '23'); INSERT INTO `t_user` VALUES ('9', 'liyintao123', '23123'); -- ---------------------------- -- Table structure for `user_t` -- ---------------------------- DROP TABLE IF EXISTS `user_t`; CREATE TABLE `user_t` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(40) NOT NULL, `password` varchar(255) NOT NULL, `age` int(4) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user_t -- ---------------------------- INSERT INTO `user_t` VALUES ('1', '测试', 'sfasgfaf', '24');
看完上述内容,你们掌握在Maven使用SSM框架实现对数据库进行增删改查操作的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。