Mybatis集成Spring的实例代码_动力节点Java 学院整理
所需要用到的其他工具或技术:
项目管理工具 : maven
前台web展示:jsp
其他框架:spring, spring mvc
数据库 : derby
新建一个maven的web项目
maven dependencies:
<!-- spring --> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-context</artifactid> <version>4.0.0.release</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-webmvc</artifactid> <version>4.0.0.release</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-tx</artifactid> <version>4.0.0.release</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-jdbc</artifactid> <version>4.0.0.release</version> </dependency> <!-- aspectj --> <dependency> <groupid>org.aspectj</groupid> <artifactid>aspectjrt</artifactid> <version>1.6.10</version> </dependency> <!-- logging --> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-api</artifactid> <version>1.6.6</version> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactid>jcl-over-slf4j</artifactid> <version>1.6.6</version> <scope>runtime</scope> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-log4j12</artifactid> <version>1.6.6</version> <scope>runtime</scope> </dependency> <!-- @inject --> <dependency> <groupid>javax.inject</groupid> <artifactid>javax.inject</artifactid> <version>1</version> </dependency> <!-- servlet --> <dependency> <groupid>javax.servlet</groupid> <artifactid>servlet-api</artifactid> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupid>javax.servlet.jsp</groupid> <artifactid>jsp-api</artifactid> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupid>javax.servlet</groupid> <artifactid>jstl</artifactid> <version>1.2</version> </dependency> <!-- mybatis --> <dependency> <groupid>org.mybatis</groupid> <artifactid>mybatis</artifactid> <version>3.2.7</version> </dependency> <dependency> <groupid>org.mybatis</groupid> <artifactid>mybatis-spring</artifactid> <version>1.2.1</version> </dependency> <!-- test --> <dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <version>4.9</version> <scope>test</scope> </dependency> <!-- derby --> <dependency> <groupid>org.apache.derby</groupid> <artifactid>derby</artifactid> <version>10.10.2.0</version> </dependency> <dependency> <groupid>org.apache.derby</groupid> <artifactid>derbyclient</artifactid> <version>10.10.2.0</version> </dependency>
sql建表及数据插入
create table user_test_tb( id int primary key, username varchar(20) not null, password varchar(20) not null, nickname varchar(20) not null ); insert into user_test_tb values(1,'1st','111','jack'); insert into user_test_tb values(2,'2nd','222','rose'); insert into user_test_tb values(3,'3rd','333','will');
web.xml(scr/main/webapp/web-inf下)
<?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 的配置 --> <context-param> <param-name>contextconfiglocation</param-name> <param-value>/web-inf/*context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <servlet> <servlet-name>appservlet</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appservlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
appservlet-servlet.xml(spring的servlet配置文件scr/main/webapp/web-inf下)
<?xml version="1.0" encoding="utf-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemalocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 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"> <!-- 开启annotation支持 --> <annotation-driven /> <!-- spring的渲染层配置 --> <beans:bean class="org.springframework.web.servlet.view.internalresourceviewresolver"> <beans:property name="prefix" value="/web-inf/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <!-- spring的annotation默认扫描包 --> <context:component-scan base-package="com.bjpowernode.practice" /> <!-- 引入其他spring配置文件 --> <beans:import resource="classpath:applicationcontext.xml" /> </beans:beans>
jsp文件
show.jsp(src/main/webapp/web-inf/views目录下) <%@ page language="java" contenttype="text/html; charset=iso-8859-1" pageencoding="iso-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>show all users</title> <style type="text/css"> *{ margin: 0px; padding: 0px; } </style> </head> <body> <table border="1px" bordercolor="green"> <thead> <tr> <th>user_name</th> <th>password</th> <th>nick_name</th> <th>edit</th> <th>delete</th> </tr> <c:foreach items="${users}" var="user" varstatus="status"> <tr> <td>${user.username}</td> <td>${user.password}</td> <td>${user.nickname}</td> <td><a href="update/${user.id}" rel="external nofollow" >edit</a></td> <td><a href="delete/${user.id}" rel="external nofollow" >delete</a></td> </tr> </c:foreach> </thead> </table> <a href="insert" rel="external nofollow" >add new user</a> </body> </html>
update.jsp(src/main/webapp/web-inf/views目录下)
<%@ page language="java" contenttype="text/html; charset=iso-8859-1" pageencoding="iso-8859-1"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>update profile</title> </head> <body> <form action="${user.id}" method="post"> user id:${user.id}<br> username:<input type="text" name="username" value="${user.username}"/><br> password:<input type="text" name="password" value="${user.password}"/><br> nickname:<input type="text" name="nickname" value="${user.nickname}"/><br> <input type="submit" value="submit"> </form> </body> </html>
insert.jsp(src/main/webapp/web-inf/views目录下)
<%@ page language="java" contenttype="text/html; charset=iso-8859-1" pageencoding="iso-8859-1"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>insert profile</title> </head> <body> <form action="" method="post"> user id:<input type="text" name="id"><br> username:<input type="text" name="username" /><br> password:<input type="text" name="password"/><br> nickname:<input type="text" name="nickname"/><br> <input type="submit" value="submit"> </form> </body> </html>
applicationcontext.xml(spring的application配置文件在src/main/resources目录下)
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd"> <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer"> <property name="basepackage" value="com.bjpowernode.practice" /> <property name="sqlsessionfactorybeanname" value="derbysqlsessionfactory" /> </bean> <!-- 配置derby驱动数据源 --> <bean id="derbydatasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource"> <property name="driverclassname" value="org.apache.derby.jdbc.clientdriver" /> <property name="url" value="jdbc:derby://localhost:1527/freud;create=true" /> </bean> <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean" name="derbysqlsessionfactory"> <property name="datasource" ref="derbydatasource" /> <property name="mapperlocations" value="classpath*:com/freud/practice/*mapper.xml" /> </bean> <!-- 事务管理器 --> <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager"> <property name="datasource" ref="derbydatasource" /> </bean> <!-- 开启基于注解的事务 --> <tx:annotation-driven /> </beans>
java文件
usercontroller.java(在src/main/java/com.bjpowernode.practice.controller目录下)
package com.bjpowernode.practice.controller; import com.bjpowernode.practice.user; import com.bjpowernode.practice.usermapper; import java.util.list; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.controller; import org.springframework.ui.model; 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.config.annotation.enablewebmvc; @enablewebmvc @controller public class usercontroller { @autowired private usermapper usermapper; /** * * 获得所有的user信息 * * @param model * @return */ @requestmapping(value = {"/", ""}, method = requestmethod.get) public string getalluser(model model) { list<user> users = usermapper.getusers(); system.out.println("show all user size:" + users.size()); model.addattribute("users", users); return "show"; } /** * * insert的get请求,跳转到insert的view即insert.jsp * * @return */ @requestmapping(value = {"/insert", ""}, method = requestmethod.get) public string insertuser() { return "insert"; } /** * * insert的post请求,执行插入操作并返回showall页面 * * @param user * @return */ @requestmapping(value = {"/insert", ""}, method = requestmethod.post) public string insertuserpost(user user) { usermapper.insertuser(user); return "redirect:/"; } /** * * update的get请求,跳转到update的view即update.jsp * * @param id * @param model * @return */ @requestmapping(value = {"/update/{id}", ""}, method = requestmethod.get) public string updateuser(@pathvariable string id, model model) { model.addattribute("user", usermapper.getuser(integer.valueof(id))); return "update"; } /** * * update的post请求,执行更新操作并返回showall页面 * * @param id * @param user * @return */ @requestmapping(value = {"/update/{id}", ""}, method = requestmethod.post) public string updateuserpost(@pathvariable string id, user user) { usermapper.updateuser(user); return "redirect:/"; } /** * * 通过id删除user * * @param id * @return */ @requestmapping(value = {"/delete/{id}", ""}, method = requestmethod.get) public string deleteuser(@pathvariable int id) { usermapper.deleteuser(id); return "redirect:/"; } }
user.java(在src/main/java/com.bjpowernode.practice)
package com.bjpowernode.practice; /** * * user 对象。 * * @author freud kang * */ public class user { private integer id; private string username; private string password; private string nickname; public integer getid() { return id; } public void setid(integer id) { this.id = id; } public string getusername() { return username; } public void setusername(string username) { this.username = username; } public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } public string getnickname() { return nickname; } public void setnickname(string nickname) { this.nickname = nickname; } }
usermapper.java(在src/main/java/com.bjpowernode.practice目录下)
package com.bjpowernode.practice; import java.util.list; public interface usermapper { /** * * 获得所有user * * @return */ public list<user> getusers(); /** * * 通过id获得user * * @param id * @return */ public user getuser(int id); /** * * 插入user * * @param user */ public void insertuser(user user); /** * * 更新user * * @param user */ public void updateuser(user user); /** * * 通过id删除user * * @param userid */ public void deleteuser(int userid); }
usermapper.xml(mybatis的mapper配置文件,在src/main/java/com.bjpowernode.practice目录下)
<?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.bjpowernode.practice.usermapper"> <!-- 查询 --> <select id="getusers" resulttype="com.bjpowernode.practice.user"> select * from user_test_tb </select> <!-- 查询 --> <select id="getuser" resulttype="com.bjpowernode.practice.user"> select * from user_test_tb where id=#{id} </select> <!-- 插入 --> <insert id="insertuser"> insert into user_test_tb values(#{id},#{username},#{password},#{nickname}) </insert> <!-- 更改 --> <update id="updateuser"> update user_test_tb set username = #{username}, password = #{password}, nickname = #{nickname} where id = #{id} </update> <!-- 删除 --> <delete id="deleteuser"> delete from user_test_tb where id=#{id} </delete> </mapper>
总结
以上所述是小编给大家介绍的mybatis集成spring的实例代码,希望对大家有所帮助
上一篇: mysql备份的三种方式详解
下一篇: Java使用Ajax实现跨域上传图片功能