查看: 427|回复: 0

[Java学习] Mybatis集成Spring的实例代码_动力节点Java 学院整理

发表于 2017-10-6 09:07:45
尚学堂AD

所需要用到的其他工具或技术:

项目管理工具 : Maven

前台WEB展示:JSP

其他框架:Spring, Spring MVC

数据库 : Derby

新建一个Maven的Web项目

Maven Dependencies:

  1. <!-- Spring -->
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>4.0.0.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework</groupId>
  9. <artifactId>spring-webmvc</artifactId>
  10. <version>4.0.0.RELEASE</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework</groupId>
  14. <artifactId>spring-tx</artifactId>
  15. <version>4.0.0.RELEASE</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework</groupId>
  19. <artifactId>spring-jdbc</artifactId>
  20. <version>4.0.0.RELEASE</version>
  21. </dependency>
  22. <!-- AspectJ -->
  23. <dependency>
  24. <groupId>org.aspectj</groupId>
  25. <artifactId>aspectjrt</artifactId>
  26. <version>1.6.10</version>
  27. </dependency>
  28. <!-- Logging -->
  29. <dependency>
  30. <groupId>org.slf4j</groupId>
  31. <artifactId>slf4j-api</artifactId>
  32. <version>1.6.6</version>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.slf4j</groupId>
  36. <artifactId>jcl-over-slf4j</artifactId>
  37. <version>1.6.6</version>
  38. <scope>runtime</scope>
  39. </dependency>
  40. <dependency>
  41. <groupId>org.slf4j</groupId>
  42. <artifactId>slf4j-log4j12</artifactId>
  43. <version>1.6.6</version>
  44. <scope>runtime</scope>
  45. </dependency>
  46. <!-- @Inject -->
  47. <dependency>
  48. <groupId>javax.inject</groupId>
  49. <artifactId>javax.inject</artifactId>
  50. <version>1</version>
  51. </dependency>
  52. <!-- Servlet -->
  53. <dependency>
  54. <groupId>javax.servlet</groupId>
  55. <artifactId>servlet-api</artifactId>
  56. <version>2.5</version>
  57. <scope>provided</scope>
  58. </dependency>
  59. <dependency>
  60. <groupId>javax.servlet.jsp</groupId>
  61. <artifactId>jsp-api</artifactId>
  62. <version>2.1</version>
  63. <scope>provided</scope>
  64. </dependency>
  65. <dependency>
  66. <groupId>javax.servlet</groupId>
  67. <artifactId>jstl</artifactId>
  68. <version>1.2</version>
  69. </dependency>
  70. <!-- Mybatis -->
  71. <dependency>
  72. <groupId>org.mybatis</groupId>
  73. <artifactId>mybatis</artifactId>
  74. <version>3.2.7</version>
  75. </dependency>
  76. <dependency>
  77. <groupId>org.mybatis</groupId>
  78. <artifactId>mybatis-spring</artifactId>
  79. <version>1.2.1</version>
  80. </dependency>
  81. <!-- Test -->
  82. <dependency>
  83. <groupId>junit</groupId>
  84. <artifactId>junit</artifactId>
  85. <version>4.9</version>
  86. <scope>test</scope>
  87. </dependency>
  88. <!-- Derby -->
  89. <dependency>
  90. <groupId>org.apache.derby</groupId>
  91. <artifactId>derby</artifactId>
  92. <version>10.10.2.0</version>
  93. </dependency>
  94. <dependency>
  95. <groupId>org.apache.derby</groupId>
  96. <artifactId>derbyclient</artifactId>
  97. <version>10.10.2.0</version>
  98. </dependency>
复制代码

SQL建表及数据插入

  1. CREATE TABLE USER_TEST_TB(
  2. ID INT PRIMARY KEY,
  3. USERNAME VARCHAR(20) NOT NULL,
  4. PASSWORD VARCHAR(20) NOT NULL,
  5. NICKNAME VARCHAR(20) NOT NULL
  6. );
  7. INSERT INTO USER_TEST_TB VALUES(1,'1st','111','Jack');
  8. INSERT INTO USER_TEST_TB VALUES(2,'2nd','222','Rose');
  9. INSERT INTO USER_TEST_TB VALUES(3,'3rd','333','Will');
复制代码

web.xml(scr/main/webapp/WEB-INF下)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  5. <!-- Spring 的配置 -->
  6. <context-param>
  7. <param-name>contextConfigLocation</param-name>
  8. <param-value>/WEB-INF/*Context.xml</param-value>
  9. </context-param>
  10. <listener>
  11. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  12. </listener>
  13. <servlet>
  14. <servlet-name>appServlet</servlet-name>
  15. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  16. <load-on-startup>1</load-on-startup>
  17. </servlet>
  18. <servlet-mapping>
  19. <servlet-name>appServlet</servlet-name>
  20. <url-pattern>/</url-pattern>
  21. </servlet-mapping>
  22. </web-app>
复制代码

appServlet-servlet.xml(Spring的Servlet配置文件scr/main/webapp/WEB-INF下)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans:beans xmlns="http://www.springframework.org/schema/mvc"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:beans="http://www.springframework.org/schema/beans"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
  7. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  9. <!-- 开启Annotation支持 -->
  10. <annotation-driven />
  11. <!-- Spring的渲染层配置 -->
  12. <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  13. <beans:property name="prefix" value="/WEB-INF/views/" />
  14. <beans:property name="suffix" value=".jsp" />
  15. </beans:bean>
  16. <!-- Spring的Annotation默认扫描包 -->
  17. <context:component-scan base-package="com.bjpowernode.practice" />
  18. <!-- 引入其他Spring配置文件 -->
  19. <beans:import resource="classpath:applicationContext.xml" />
  20. </beans:beans>
复制代码

JSP文件

  1. show.jsp(src/main/webapp/WEB-INF/views目录下)
  2. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  3. pageEncoding="ISO-8859-1"%>
  4. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  9. <title>Show All Users</title>
  10. <style type="text/css">
  11. *{
  12. margin: 0px;
  13. padding: 0px;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <table border="1px" bordercolor="green">
  19. <thead>
  20. <tr>
  21. <th>USER_NAME</th>
  22. <th>PASSWORD</th>
  23. <th>NICK_NAME</th>
  24. <th>EDIT</th>
  25. <th>DELETE</th>
  26. </tr>
  27. <c:forEach items="${users}" var="user" varStatus="status">
  28. <tr>
  29. <td>${user.username}</td>
  30. <td>${user.password}</td>
  31. <td>${user.nickname}</td>
  32. <td><a href="update/${user.id}" rel="external nofollow" >edit</a></td>
  33. <td><a href="delete/${user.id}" rel="external nofollow" >delete</a></td>
  34. </tr>
  35. </c:forEach>
  36. </thead>
  37. </table>
  38. <a href="insert" rel="external nofollow" >Add new User</a>
  39. </body>
  40. </html>
复制代码

update.jsp(src/main/webapp/WEB-INF/views目录下)

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2. pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  7. <title>Update Profile</title>
  8. </head>
  9. <body>
  10. <form action="${user.id}" method="post">
  11. User ID:${user.id}<br>
  12. Username:<input type="text" name="username" value="${user.username}"/><br>
  13. Password:<input type="text" name="password" value="${user.password}"/><br>
  14. Nickname:<input type="text" name="nickname" value="${user.nickname}"/><br>
  15. <input type="submit" value="submit">
  16. </form>
  17. </body>
  18. </html>
复制代码

insert.jsp(src/main/webapp/WEB-INF/views目录下)

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2. pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  7. <title>Insert Profile</title>
  8. </head>
  9. <body>
  10. <form action="" method="post">
  11. User Id:<input type="text" name="id"><br>
  12. Username:<input type="text" name="username" /><br>
  13. Password:<input type="text" name="password"/><br>
  14. Nickname:<input type="text" name="nickname"/><br>
  15. <input type="submit" value="submit">
  16. </form>
  17. </body>
  18. </html>
复制代码

applicationContext.xml(Spring的Application配置文件在src/main/resources目录下)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
  8. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  10. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
  11. http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd
  12. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  13. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  14. http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd">
  15. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  16. <property name="basePackage" value="com.bjpowernode.practice" />
  17. <property name="sqlSessionFactoryBeanName" value="derbySqlSessionFactory" />
  18. </bean>
  19. <!-- 配置Derby驱动数据源 -->
  20. <bean id="derbyDataSource"
  21. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  22. <property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver" />
  23. <property name="url" value="jdbc:derby://localhost:1527/freud;create=true" />
  24. </bean>
  25. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
  26. name="derbySqlSessionFactory">
  27. <property name="dataSource" ref="derbyDataSource" />
  28. <property name="mapperLocations" value="classpath*:com/freud/practice/*Mapper.xml" />
  29. </bean>
  30. <!-- 事务管理器 -->
  31. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  32. <property name="dataSource" ref="derbyDataSource" />
  33. </bean>
  34. <!-- 开启基于注解的事务 -->
  35. <tx:annotation-driven />
  36. </beans>
复制代码

Java文件

UserController.Java(在src/main/java/com.bjpowernode.practice.controller目录下)

  1. package com.bjpowernode.practice.controller;
  2. import com.bjpowernode.practice.User;
  3. import com.bjpowernode.practice.UserMapper;
  4. import java.util.List;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.web.bind.annotation.PathVariable;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RequestMethod;
  11. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  12. @EnableWebMvc
  13. @Controller
  14. public class UserController
  15. {
  16. @Autowired
  17. private UserMapper userMapper;
  18. /**
  19. *
  20. * 获得所有的User信息
  21. *
  22. * @param model
  23. * @return
  24. */
  25. @RequestMapping(value = {"/", ""}, method = RequestMethod.GET)
  26. public String getAllUser(Model model)
  27. {
  28. List<User> users = userMapper.getUsers();
  29. System.out.println("Show all user size:" + users.size());
  30. model.addAttribute("users", users);
  31. return "show";
  32. }
  33. /**
  34. *
  35. * INSERT的GET请求,跳转到Insert的View即insert.jsp
  36. *
  37. * @return
  38. */
  39. @RequestMapping(value = {"/insert", ""}, method = RequestMethod.GET)
  40. public String insertUser()
  41. {
  42. return "insert";
  43. }
  44. /**
  45. *
  46. * INSERT的POST请求,执行插入操作并返回ShowAll页面
  47. *
  48. * @param user
  49. * @return
  50. */
  51. @RequestMapping(value = {"/insert", ""}, method = RequestMethod.POST)
  52. public String insertUserPOST(User user)
  53. {
  54. userMapper.insertUser(user);
  55. return "redirect:/";
  56. }
  57. /**
  58. *
  59. * UPDATE的GET请求,跳转到update的View即update.jsp
  60. *
  61. * @param id
  62. * @param model
  63. * @return
  64. */
  65. @RequestMapping(value = {"/update/{id}", ""}, method = RequestMethod.GET)
  66. public String updateUser(@PathVariable String id, Model model)
  67. {
  68. model.addAttribute("user", userMapper.getUser(Integer.valueOf(id)));
  69. return "update";
  70. }
  71. /**
  72. *
  73. * UPDATE的POST请求,执行更新操作并返回ShowAll页面
  74. *
  75. * @param id
  76. * @param user
  77. * @return
  78. */
  79. @RequestMapping(value = {"/update/{id}", ""}, method = RequestMethod.POST)
  80. public String updateUserPOST(@PathVariable String id, User user)
  81. {
  82. userMapper.updateUser(user);
  83. return "redirect:/";
  84. }
  85. /**
  86. *
  87. * 通过Id删除USER
  88. *
  89. * @param id
  90. * @return
  91. */
  92. @RequestMapping(value = {"/delete/{id}", ""}, method = RequestMethod.GET)
  93. public String deleteUser(@PathVariable int id)
  94. {
  95. userMapper.deleteUser(id);
  96. return "redirect:/";
  97. }
  98. }
复制代码

User.java(在src/main/java/com.bjpowernode.practice)

  1. package com.bjpowernode.practice;
  2. /**
  3. *
  4. * User 对象。
  5. *
  6. * @author Freud Kang
  7. *
  8. */
  9. public class User
  10. {
  11. private Integer id;
  12. private String username;
  13. private String password;
  14. private String nickname;
  15. public Integer getId()
  16. {
  17. return id;
  18. }
  19. public void setId(Integer id)
  20. {
  21. this.id = id;
  22. }
  23. public String getUsername()
  24. {
  25. return username;
  26. }
  27. public void setUsername(String username)
  28. {
  29. this.username = username;
  30. }
  31. public String getPassword()
  32. {
  33. return password;
  34. }
  35. public void setPassword(String password)
  36. {
  37. this.password = password;
  38. }
  39. public String getNickname()
  40. {
  41. return nickname;
  42. }
  43. public void setNickname(String nickname)
  44. {
  45. this.nickname = nickname;
  46. }
  47. }
复制代码

UserMapper.java(在src/main/java/com.bjpowernode.practice目录下)

  1. package com.bjpowernode.practice;
  2. import java.util.List;
  3. public interface UserMapper
  4. {
  5. /**
  6. *
  7. * 获得所有User
  8. *
  9. * @return
  10. */
  11. public List<User> getUsers();
  12. /**
  13. *
  14. * 通过Id获得User
  15. *
  16. * @param id
  17. * @return
  18. */
  19. public User getUser(int id);
  20. /**
  21. *
  22. * 插入User
  23. *
  24. * @param user
  25. */
  26. public void insertUser(User user);
  27. /**
  28. *
  29. * 更新User
  30. *
  31. * @param user
  32. */
  33. public void updateUser(User user);
  34. /**
  35. *
  36. * 通过Id删除User
  37. *
  38. * @param userId
  39. */
  40. public void deleteUser(int userId);
  41. }
复制代码

UserMapper.xml(mybatis的mapper配置文件,在src/main/java/com.bjpowernode.practice目录下)

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.bjpowernode.practice.UserMapper">
  6. <!-- 查询 -->
  7. <select id="getUsers" resultType="com.bjpowernode.practice.User">
  8. select *
  9. from USER_TEST_TB
  10. </select>
  11. <!-- 查询 -->
  12. <select id="getUser" resultType="com.bjpowernode.practice.User">
  13. select *
  14. from USER_TEST_TB
  15. where ID=#{id}
  16. </select>
  17. <!-- 插入 -->
  18. <insert id="insertUser">
  19. insert into
  20. USER_TEST_TB
  21. values(#{id},#{username},#{password},#{nickname})
  22. </insert>
  23. <!-- 更改 -->
  24. <update id="updateUser">
  25. update USER_TEST_TB set
  26. USERNAME = #{username},
  27. PASSWORD = #{password},
  28. NICKNAME = #{nickname}
  29. where ID = #{id}
  30. </update>
  31. <!-- 删除 -->
  32. <delete id="deleteUser">
  33. delete from USER_TEST_TB where ID=#{id}
  34. </delete>
  35. </mapper>
复制代码

总结

以上所述是小编给大家介绍的Mybatis集成Spring的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对程序员之家网站的支持!



回复

使用道具 举报