Spirngmvc integrates mybatis to implement CRUD and mybatiscrud
1. Create a simple User table
Create table 'users '(
'Id' int (20) not null AUTO_INCREMENT,
'Name' varchar (20) not null,
'Age' int (20) default null,
Primary key ('id ')
) ENGINE = InnoDB AUTO_INCREMENT = 19 default charset = utf8;
------------------------------
-- Records of users
------------------------------
Insert into 'users' VALUES ('1', 'duchong', '10 ');
Insert into 'users' VALUES ('2', 'huang Chunyu ', '12 ');
Insert into 'users' VALUES ('11', 'wenje', '2 ');
Insert into 'users' VALUES ('12', 'he Liang ', '20 ');
Insert into 'users' VALUES ('13', 'superge', '25 ');
Insert into 'users' VALUES ('14', 'abao', '10 ');
2. Use myeclipse to build a web project ssi
2.1. jar package
2.2 directory structure
2.3 springmvc core servlet ssi-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: context = "http://www.springframework.org/schema/context"
Xmlns: mvc = "http://www.springframework.org/schema/mvc"
Xmlns: aop = "http://www.springframework.org/schema/aop"
Xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd ">
<Context: component-scan base-package = "org. ssi. controller"/>
<! -- Automatically register the parser and adapter -->
<Mvc: annotation-driven/>
<Mvc: default-servlet-handler/>
<Aop: aspectj-autoproxy proxy-target-class = "true"/>
<! -- View parser distributor -->
<Bean class = "org. springframework. web. servlet. view. ContentNegotiatingViewResolver">
<! -- Check the request suffix first. If no match exists, spring checks the ContentType set in the request header to find the appropriate mediaType and returns a mediaType.
MediaTypes stores the mediaType corresponding to your request suffix or Parameter
-->
<Property name = "mediaTypes">
<Map>
<Entry key = "atom" value = "application/atom + xml"/>
<Entry key = "html" value = "text/html"/>
<Entry key = "json" value = "application/json"/>
</Map>
</Property>
<! -- Specific parser -->
<Property name = "viewResolvers">
<List>
<Bean class = "org. springframework. web. servlet. view. BeanNameViewResolver"/>
<Bean class = "org. springframework. web. servlet. view. InternalResourceViewResolver">
<Property name = "prefix" value = "/jsp/"/>
<Property name = "suffix" value = ". jsp"/>
</Bean>
</List>
</Property>
</Bean>
</Beans>
2.4. web. xml
<? Xml version = "1.0" encoding = "UTF-8"?>
<Web-app xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version = "2.5">
<Display-name> </display-name>
<Welcome-file-list>
<Welcome-file> index. jsp </welcome-file>
</Welcome-file-list>
<Servlet>
<Servlet-name> ssi </servlet-name>
<Servlet-class> org. springframework. web. servlet. DispatcherServlet </servlet-class>
<Load-on-startup> 1 </load-on-startup>
</Servlet>
<Servlet-mapping>
<Servlet-name> ssi </servlet-name>
<Url-pattern>/</url-pattern>
</Servlet-mapping>
<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>
<Listener>
<Listener-class> org. springframework. web. context. ContextLoaderListener </listener-class>
</Listener>
<Context-param>
<Param-name> contextConfigLocation </param-name>
<Param-value>
Classpath: applicationContext. xml
</Param-value>
</Context-param>
<Session-config>
<Session-timeout> 0 </session-timeout>
</Session-config>
</Web-app>
2.5. conf. xml can be omitted from this file.
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE configuration PUBLIC "-// mybatis.org//DTD Config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd ">
<Configuration>
<TypeAliases>
<TypeAlias type = "org. ssi. model. User" alias = "User"/>
</TypeAliases>
</Configuration>
2.6 configure spring container 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: aop = "The http://www.springframework.org/schema/aop" xmlns: tx = "The http://www.springframework.org/schema/tx"
Xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
">
<! -- Load the database property configuration file
<Context: property-placeholder location = "classpath: db. properties" ignore-unresolvable = "true"/>
-->
<Bean id = "dataSource" class = "org. apache. commons. dbcp. BasicDataSource">
<! --
<Property name = "driverClassName" value = "$ {jdbc. driver}"> </property>
<Property name = "url" value = "$ {jdbc. url}"> </property>
<Property name = "password" value = "$ {jdbc. password}"> </property>
<Property name = "username" value = "$ {jdbc. username}"> </property>
-->
<Property name = "driverClassName" value = "com. mysql. jdbc. Driver"> </property>
<Property name = "url" value = "jdbc: mysql: // localhost: 3306/mybatis"> </property>
<Property name = "username" value = "root"> </property>
<Property name = "password" value = "root"> </property>
<! -- MaxActive: Maximum number of connections -->
<Property name = "maxActive" value = "150"/>
<! -- MinIdle: Minimum idle connection -->
<Property name = "minIdle" value = "5"/>
<! -- MaxIdle: Maximum number of idle connections -->
<Property name = "maxIdle" value = "20"/>
<! -- InitialSize: Initialize the connection -->
<Property name = "initialSize" value = "30"/>
<! -- Whether to print the connection when the connection is leaked -->
<Property name = "logAbandoned" value = "true"/>
<! -- RemoveAbandoned: whether to automatically recycle the timeout connection -->
<Property name = "removeAbandoned" value = "true"/>
<! -- RemoveAbandonedTimeout: timeout (in seconds) -->
<Property name = "removeAbandonedTimeout" value = "10"/>
<! -- MaxWait: the timeout wait time is measured in milliseconds. The unit is 1000 or 60 seconds. -->
<Property name = "maxWait" value = "1000"/>
<! -- The time value of sleep during idle connection to the recycler thread running, in milliseconds. -->
<Property name = "timeBetweenEvictionRunsMillis" value = "10000"/>
<! -- Check the number of connections for each idle connection to the recycler thread (if any) -->
<Property name = "numTestsPerEvictionRun" value = "10"/>
<! -- 1000*60*30 connections are kept idle in the pool without being idle connection to the recycler thread -->
<Property name = "minEvictableIdleTimeMillis" value = "10000"/>
</Bean>
<Bean id = "sqlSessionFactory" class = "org. mybatis. spring. SqlSessionFactoryBean">
<Property name = "configLocation" value = "classpath: conf. xml"/>
<Property name = "dataSource" ref = "dataSource"/>
<Property name = "mapperLocations" value = "classpath: org/ssi/mapper/*. xml"/>
</Bean>
<! -- Configure the scanner -->
<Bean class = "org. mybatis. spring. mapper. MapperScannerConfigurer">
<! -- Scan the org. ssi. dao package and all the ing interface classes under its sub-package -->
<Property name = "basePackage" value = "org. ssi. dao"/>
<Property name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory"/>
</Bean>
<! -- Configure things -->
<Bean id = "txManager"
Class = "org. springframework. jdbc. datasource. DataSourceTransactionManager">
<Property name = "dataSource" ref = "dataSource"/>
</Bean>
<! -- Annotation transaction -->
<Tx: annotation-driven transaction-manager = "txManager"/>
<Context: annotation-config/>
<! --
-->
<Context: component-scan base-package = "org. ssi. service, org. ssi. dao,"/>
</Beans>
2.7 dao interface. Implementation classes are implemented using mybatis instead of implementation classes.
Package org. ssi. dao;
Import java. util. List;
Import org. ssi. model. User;
Public interface UserMapperI {
/**
* Add
* @ Param user
*/
Public void addUser (User user );
/**
* Change
* @ Param user
*/
Public void updateUser (User user );
/**
* Delete
* @ Param id
*/
Public void deleteUser (int id );
/**
* Query
* @ Param id
* @ Return
*/
Public User getUser (int id );
/**
* Query all
* @ Return
*/
Public List <User> getAllUsers ();
}
Corresponds to the class file and path in the configuration file,
2.8. pojo class user. java
Package org. ssi. model;
Public class User {
Private int id;
Private String name;
Private int age;
Public User (int id, String name, int age ){
Super ();
This. id = id;
This. name = name;
This. age = age;
}
Public User (){
Super ();
}
Public int getId (){
Return id;
}
Public void setId (int id ){
This. id = id;
}
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}
Public int getAge (){
Return age;
}
Public void setAge (int age ){
This. age = age;
}
@ Override
Public String toString (){
Return "User [id =" + id + ", name =" + name + ", age =" + age + "]";
}
}
2.9 UserMapperI. xml
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd ">
<! --
Specify a unique namespace for this mapper. Set the namespace value to package name + SQL ing file name. This ensures that the namespace value is unique.
For example, namespace = "org. ssi. dao. UserMapperI" is org. ssi. dao (package name) + UserMapperI (remove Suffix from userMapperI. xml file)
-->
<Mapper namespace = "org. ssi. dao. UserMapperI">
<! -- <ResultMap> tags are used to deal with the mismatch between attributes of pojo objects and table fields.
<ResultMap id = "userResultMap" type = "User">
<Id property = "id" column = "userid"/>
<Result property = "name" column = "username"/>
<Result property = "age" column = "age"/>
</ResultMap>
-->
<! --
Compile the query SQL statement in the select tag and set the id attribute of the select tag to getUser. The id attribute value must be unique,
The parameterType attribute cannot be used repeatedly to specify the parameter type used for query. The resultType attribute indicates the type of the returned result set.
ResultType = "org. mybatis. model. User" indicates that the query result is encapsulated into a User Class Object and returned
The User class is the entity class corresponding to the users table.
-->
<! --
Obtain a user object by id query.
-->
<Select id = "getUser" parameterType = "int"
ResultType = "User">
Select * from users where id =#{ id}
</Select>
<Insert id = "addUser" parameterType = "User">
Insert into users (name, age) values (# {name}, # {age })
</Insert>
<Delete id = "deleteUser" parameterType = "int">
Delete from users where id =#{ id}
</Delete>
<Update id = "updateUser" parameterType = "User">
Update users set name = # {name}, age = # {age} where id = # {id}
</Update>
<Select id = "getAllUsers" resultType = "User">
Select * from users
</Select>
</Mapper>
The operation IDs in the xml file must correspond to the method names in the dao interface one by one. If not, an error is returned.
According to the above configuration, springmvc's overall architecture of integrating mybatis has been completed,
3. write code for testing
Controller SsiController. java
Package org. ssi. controller;
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. PathVariable;
Import org. springframework. web. bind. annotation. RequestMapping;
Import org. springframework. web. bind. annotation. RequestMethod;
Import org. ssi. dao. UserMapperI;
Import org. ssi. model. User;
@ Controller
@ RequestMapping (value = "/controller ")
Public class SsiController {
@ Autowired
Private UserMapperI umi;
Private List <User> ulist;
@ RequestMapping (value = "/all", method = RequestMethod. GET)
Public String uList (HttpServletRequest request ){
Ulist = this. umi. getAllUsers ();
For (int I = 0; I <ulist. size (); I ++ ){
System. out. println (ulist. get (I ));
}
Request. setAttribute ("ulist", ulist );
Return "allusers ";
}
@ RequestMapping (value = "/addu", method = RequestMethod. POST)
Public String addU (User u ){
This. umi. addUser (u );
Return "redirect: all ";
}
@ RequestMapping (value = "/delete/{id}", method = RequestMethod. GET)
Public String deleteU (HttpServletRequest request, @ PathVariable Integer id ){
This. umi. deleteUser (id );
Return "redirect:/controller/all ";
}
@ RequestMapping (value = "/get/{id}", method = RequestMethod. GET)
Public String getUserById (HttpServletRequest request, @ PathVariable Integer id ){
User u = this. umi. getUser (id );
Request. setAttribute ("user", u );
Return "userinfo ";
}
@ RequestMapping (value = "/update/{id}", method = RequestMethod. POST)
Public String updateU (HttpServletRequest request, @ PathVariable Integer id, User u ){
User uu = this. umi. getUser (id );
Uu. setName (u. getName ());
Uu. setAge (u. getAge ());
This. umi. updateUser (uu );
Return "redirect:/controller/all ";
}
}
3.1 new test
Index. jsp
<% @ Page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %>
<%
String path = request. getContextPath ();
String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/";
%>
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Base href = "<% = basePath %>">
<Title> Add User </title>
<Meta http-equiv = "pragma" content = "no-cache">
<Meta http-equiv = "cache-control" content = "no-cache">
<Meta http-equiv = "expires" content = "0">
<Meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
<Meta http-equiv = "description" content = "This is my page">
<! --
<Link rel = "stylesheet" type = "text/css" href = "styles.css">
-->
</Head>
<Body>
<Form action = "controller/addu" method = "post">
Name: <input name = "name" type = "text"> <br>
Age: <input name = "age" type = "text"> <br>
<Input type = "submit" value = "submit">
</Form>
<Br>
</Body>
</Html>
Before adding:
Add:
After adding:
Click edit 19, Obama
Userinfo. jsp
<% @ Page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %>
<%
String path = request. getContextPath ();
String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/";
%>
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Base href = "<% = basePath %>">
<Title> UserInfo </title>
<Meta http-equiv = "pragma" content = "no-cache">
<Meta http-equiv = "cache-control" content = "no-cache">
<Meta http-equiv = "expires" content = "0">
<Meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
<Meta http-equiv = "description" content = "This is my page">
<! --
<Link rel = "stylesheet" type = "text/css" href = "styles.css">
-->
</Head>
<Body>
<P align = "center"> <font size = "20"> UserInfo Edit </font> </p>
<Div align = "center">
<Form action = "controller/update/$ {user. id}" method = "post">
Name: <input type = "text" name = "name" value = "$ {user. name}"> <br>
Age: <input type = "text" name = "age" value = "$ {user. age}"> <br>
<Input type = "submit" value = "Usubmit">
</Form>
</Div>
</Body>
</Html>