SPRINGMVC, MyBatis Integrated notes

Source: Internet
Author: User
Tags button type

At this time a project just finished, the next project has not yet begun, while this time to carefully summarize the previous project used the SSM development framework. As the code and configuration for the use of SSM in the project is an independent completion of our project's overall architect, we are only responsible for the business part of the code, calling him to write the backstage, so involved in the SSM specific use I did not participate in, before simply done s (struts) SH, Not very familiar with SSM, so this period of time to build a single SSM framework Web application.

First, the jar packages required by spring, SPRINGMVC, and MyBatis are ready, imported into the Lib of the new Web project, and then started to build the structure under the Java Source Code (SRC), which I used here is a structure similar to SSH Mapper.java, Mapper.xml, DAO, Daoimpl, service, SERVICEIMPL, controller. The project directory structure is as follows.

Next, write the configuration file.

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_3_0.xsd" id= "Webapp_       ID "version=" 3.0 "> <display-name>SSM</display-name> <!--spring configuration file load-up <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:resources/spring-config .xml</param-value> </context-param> <!--Spring ApplicationContext loading <listener> &lt ;listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener > <!--MVC Controller--<servlet> <servlet-name>dispatcher</servlet-name> <servlet-c Lass>org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-va lue> classpath:resources/mvc-config.xml </param-value> </init-param> &L t;load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispa Tcher</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--the first page displayed by default -<welcome-file-list> <welcome-file>login.html</welcome-file> <welcome-file> Login.jsp</welcome-file> </welcome-file-list></web-app>

-----------------------------------------------Spring.xml--------------------------------------

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:    context= "Http://www.springframework.org/schema/context" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 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.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd " > <!--Scan DAO and service packs, controller packages are scanned in Springmvc--<context:component-scan base-package= "Com.liusk.s Erviceimpl,com.liusk.daoimpl "/> <!--data Source-<beanId= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > <property name= "driverclass" value= "COM.M Ysql.jdbc.Driver "></property> <property name=" Jdbcurl "value=" JDBC:MYSQL://LOCALHOST:3306/SSM? Characterencoding=utf-8 "></property> <property name=" user "value=" root "></property> &lt ;p roperty name= "password" value= "java" ></property> <property name= "Minpoolsize" value= "5" ></prope rty> <property name= "maxpoolsize" value= "></property> </bean> <!--session Factory--&gt    ; <bean id= "Sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" > <property name= "DataSource "Ref=" DataSource "></property> <property name=" configlocation "value=" classpath:resources/mybatis-conf Ig.xml "></property> <property name=" mapperlocations "value=" Classpath:com/liusk/mapper/*.xml "><   /property> </bean>     <!--transaction--<bean id= "Txmanager" class= "org.springframework.jdbc.datasource.DataSourceTransactionManage R "> <property name=" dataSource "ref=" DataSource "></property> </bean> <tx:advice id=" t Xadvice "transaction-manager=" Txmanager "> <tx:attributes> <tx:method name=" insert* "Propagat            ion= "REQUIRED" ></tx:method> <tx:method name= "delete*" propagation= "REQUIRED" ></tx:method> <tx:method name= "update*" propagation= "REQUIRED" ></tx:method> <tx:method name= "Select        * "propagation=" SUPPORTS "></tx:method> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id= "servicecut" expression= "Execution (public * com.liusk.service.*.* (..))"/> <aop:ad     Visor pointcut-ref= "Servicecut" advice-ref= "Txadvice"/> </aop:config> <!--spring and MyBatis integration-- <bean class= "org.Mybatis.spring.mapper.MapperScannerConfigurer "> <property name=" basepackage "value=" Com.liusk.mapper "/> </bean> </beans>

There are many ways to integrate spring and MyBatis, the above XML is the most basic configuration, you can also add other restrictions, this can be separate to Baidu search more detailed explanation.

-------------------------------------------------------Mvc-config.xml------------------------------------------------

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:    context= "Http://www.springframework.org/schema/context" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 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 "> <!--Scan Controller Package--<context:component-scan base-package=" Com.liusk.contro Ller "></context:component-scan> <!--complete Pojo of requests and annotations--<bean class=" Org.springframework.web.s Ervlet.mvc.annotation.AnnotationMethodHandlerAdapter "/> <!--page Turn resolution--<bean id=" Viewresolver "Clas s= "Org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name= "prefix" value= "/"/&G        T <property name= "suffix" value= ". JSP"/> </bean> <!--support file uploads-<bean id= "Multipartresolver" class= "Org.springframework.web.multi Part.commons.CommonsMultipartResolver "> </bean> </beans>

In the Mvcconfig, the most important work is to control the forwarding, this configuration file is the simplest forwarding, can only forward the page, if you want to forward data through Ajax, then you need to rewrite the viewresolver to implement this function.

--------------------------------------------------------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>        <!--definition aliases--    <typeAliases>        <typealias type= " Com.liusk.entity.User "alias=" User "/>    </typeAliases>    </configuration>

At this point, the configuration file section is complete.

Below is the SRC source code

----------------------------------------------------------User.java------------------------------------------------------

Package Com.liusk.entity;public class User {    private String userId;    Private String username;    private String password;        Public String getUserId () {        return userId;    }    public void Setuserid (String userId) {        This.userid = userId;    }    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;    }}

The difference between MyBatis entity classes and Hibernate entity classes is that MyBatis entity classes do not need to be loaded into spring beanfactory, but rather persist data by manipulating the mapper of the database.

-----------------------------------------------------------Usermapper.java------------------------------------------

Package Com.liusk.mapper;import Java.util.list;import Com.liusk.entity.user;public interface Usermapper {public    List<user> selectuser (user user);    public void Insertuser (user user);    Public list<user> Selectuserbyusername (String username);}

Usermapper.java when was this file loaded into spring? We know it was used in Daoimpl, and it was annotated into the Daoimpl, so it must have been loaded into beanfactory before, and I was not too sure when I first configured it when it entered Beanfactory because it didn't have any annotations. , so, based on the integration of spring and MyBatis in the spring configuration file, it is speculated that Usermapper.java is

<bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name= "basepackage" value= " Com.liusk.mapper "/></bean>

This place is loaded. Here are the detailed answers.

----------------------------------------------------------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" ><        Mapper namespace= "Com.liusk.mapper.UserMapper" > <resultmap type= "com.liusk.entity.User" id= "UserMap" >         <id column= "user_id" property= "userId" ></id> <result column= "user_name" property= "username"/> <result column= "password" property= "password"/> </resultMap> <select id= "Selectuser" para Metertype= "User" resulttype= "java.util.List" resultmap= "UserMap" > select * from User where user_name = #{usernam e} and Password = #{password} </select> <select id= "Selectuserbyusername" parametertype= "Java.lang.Stri Ng "Resulttype=" java.util.List "resultmap=" UserMap "> select * from user where user_name = #{username} </se lect> <insert id= "Insertuser" parametertype= "User" > INSERT into User values (#{useriD},#{username},#{password}) </insert> </mapper> 

This configuration file namespace the path of the corresponding interface, which is the path of Mapper.java, otherwise throws an exception. So here's a question: When did Usermapper.java load into beanfactory? Why would you use this problem? Should usermapper.xml be scanned and loaded into spring at the time of Spring's sessionfactory initialization, will this time be loaded into the beanfactory of the Usermapper.java based on this namespace, but I have not seen SPRI Ng and MyBatis's source code, so not quite understand. Based on guesswork and validation, Usermapper.java is not loaded at this time.

------------------------------------------------------Userdao--------------------------------------------

Package Com.liusk.dao;import Java.util.list;import Com.liusk.entity.user;public interface Userdao {public        List <User> selectuser (user user);        public void Insertuser (user user);        Public list<user> Selectuserbyusername (String username);}

The existence of this Userdao to my first project using SSH salute, in fact, this userdao he is an interface, can not exist, the following userservice is also the truth.

------------------------------------------------------Userdaoimpl----------------------------------------

Package Com.liusk.daoimpl;import Java.util.list;import Org.safehaus.uuid.uuidgenerator;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.repository;import Com.liusk.dao.userdao;import Com.liusk.entity.user;import Com.liusk.mapper.UserMapper; @Repositorypublic class        Userdaoimpl implements Userdao {@Autowired private usermapper usermapper;        Private Uuidgenerator Uuidgen = Uuidgenerator.getinstance ();    @Override public list<user> selectuser (user user) {return usermapper.selectuser (user);        } @Override public void Insertuser (user user) {String userId = Uuidgen.generatetimebaseduuid (). toString (); if (User.getuserid () ==null| |        User.getuserid () = = "") User.setuserid (Userid.replace ("-", ""));        System.out.println (User.getuserid ());     Usermapper.insertuser (user); } @Override Public list<user> selectuserbyusername (String username) {return UsermappEr.selectuserbyusername (username); }    }

Userdaoimpl and Userserviceimpl are similar, are implementation classes, do specific data persistence operations.

--------------------------------------------------------UserService-----------------------------------------

Package Com.liusk.service;import Java.util.list;import Com.liusk.entity.user;public interface UserService {        public void Insertuser (user user);        Public list<user> selectuser (user user);        public boolean Existuser (String username);    }

--------------------------------------------------------Userserviceimpl--------------------------------------

Package Com.liusk.serviceimpl;import Java.util.list;import org.springframework.beans.factory.annotation.Autowired ; Import Org.springframework.stereotype.service;import Com.liusk.dao.userdao;import Com.liusk.entity.user;import Com.liusk.service.UserService, @Servicepublic class Userserviceimpl implements userservice{    @Autowired    Private Userdao Userdao;        @Override public    void Insertuser (user user) {        userdao.insertuser (user);    }    @Override public    list<user> selectuser (user user) {        return userdao.selectuser (user);    @Override Public    Boolean existuser (String username) {        list<user> userlist = Userdao.selectuserbyusername (username);        if (Userlist.size () >0)            return true;        else            return false;}    }

-------------------------------------------------------Usercontroller-------------------------------------

Package Com.liusk.controller;import Java.util.list;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpsession;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.servlet.modelandview;import Com.liusk.base.usercounts;import Com.liusk.entity.User;    Import Com.liusk.service.UserService; @Controller @requestmapping ("User") public class Usercontroller {@Autowired        Private UserService UserService; @SuppressWarnings ("Rawtypes") @RequestMapping ("login.do") public Modelandview login (String username,string password,        HttpServletRequest request) {User user = new User ();        User.setusername (username);        User.setpassword (password);        List<user> userlist = Userservice.selectuser (User); if (Userlist.size () >0) {Request.setattribute ("userlist", userlist); return new MoDelandview ("index");    }else return new Modelandview ("login"); } @RequestMapping ("Regist.do") public modelandview regist (String username,string password,httpservletrequest req        uest) {User user = new User ();        User.setusername (username);        User.setpassword (password);        Boolean flag = true;        Flag = Userservice.existuser (username);        if (!flag) userservice.insertuser (user);    return new Modelandview ("login"); }}

At this point, the Java source under SRC is complete.

The following is the JSP page section.

-----------------------------------------------------login.jsp--------------------------------------------------

<%@ page language= "java" contenttype= "text/html;    Charset=utf-8 "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" "Http://www.w3.org/TR/html4/loose.dtd" >

-----------------------------------------------------index.jsp--------------------------------------------------------

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><%@ page import=" com.liusk.entity.User "%><%@ page import=" Java.util.List "%><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <% list<user> userlist = (list<user>) request.getattribute ("userlist");%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

JSP you understand that these pages are not long explanations.

Summary, will use the framework is not difficult, difficult is to write a framework out, have a dream will be brave to fly.

"Source Address acquisition

SPRINGMVC + mybatis Integration details, and the problems encountered, please refer to the following information:

Resources:

Http://www.springmvc,net/detail/6074493.html

http://my.spring.net/wangbiglei/blog/489583

http://my.springmvc.net/wangbiglei/blog/489604

SPRINGMVC, MyBatis Integrated notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.