SPRINGMVC configuration and Spring configuration?

Source: Internet
Author: User

When using SPRINGMVC recently in contact with MyBatis, the configuration file has always been the configuration of Web.xml+xx-servlet.xml (XX is the servlet name in Web. xml).
In order to integrate Mybatie, a variety of Baidu, found on the internet a lot of people said SPRINGMVC also need to configure applicationcontext.xml, according to my shallow understanding, ApplicationContext is the configuration of spring. So I'd like to ask about the configuration differences between SPRINGMVC and spring, and how the configuration file is configured for SPRINGMVC and MyBatis in combination. PS: The current use of stringbuffer form of splicing SQL, combined with ORG.SPRINGFRAMEWORK.JDBC in the nameparameterjdbctemplate to use, want to change the use of new, hope you are not hesitate to enlighten, thank you)

====================================================================================

Second-Rate Program ape
Links: https://www.zhihu.com/question/47565214/answer/136096996
Source: Know
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

SPRINGMVC is responsible for the processing of the spring control layer, and the Servlet.xml configuration file, mainly responsible for the MVC part of the configuration, such as view parsing, context processing, etc., it is important to note that The name and location of this file is allowed to be defined in the servlet configuration of Web. XML (Init-param):

 <servlet>        <servlet-name>graduation</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath:spring-servlet.xml</param-value>        </init-param>        <load-on-startup>2</load-on-startup><!--表示启动容器时候初始化-->    </servlet>    <servlet-mapping>        <servlet-name>graduation</servlet-name>        <url-pattern>/</url-pattern><!--表示对所有后缀为do的请求做spring拦截-->    </servlet-mapping>
Instead, Application.xml is used to configure spring's global properties, such as DataSource, AOP, and so on, to first add the configuration (classpath:applicationContext.xml path) to Web. xml:
<context-param>      <param-name>contextConfigLocation</param-name>      <param-value>classpath:spring-applicationContext.xml</param-value></context-param>

Here's how to combine spring with MyBatis.
In applicationcontext.xml This configuration file, we will first configure our data source:
The specific configuration is subject to the project, where Ali's Druid is used.
<bean id= "DataSource" class= "Com.alibaba.druid.pool.DruidDataSource" init-method= "Init" destroy-method= "Close" > <!--driver name--<property name= "Driverclassname" value= "${jdbc.driverclassname}"/> <! --JDBC Connect--<property name= "url" value= "${jdbc.url}"/> <!--database name---<property name = "username" value= "${jdbc.username}"/> <!--database Password--<property name= "password" value= "${jdbc.pass         Word} "/> <!--initialization size--<property name=" initialsize "value=" "/> <!--connection pool Max Usage Quantity-- <property name= "maxactive" value= "/> <!--connection pool min Free---<property name=" Minidle "value = "0"/> <!--configuration Get connection Wait timeout-<property name= "maxwait" value= "60000"/> <!--configuration interval how often Detect, detect the idle connection that needs to be closed--<property name= "Timebetweenevictionrunsmillis" value= "60000"/> <!--Configure a connection in the pool Minimum time to live-<properTy name= "Minevictableidletimemillis" value= "300000"/> <!--the test is active when the connection is idle--<property name= "Testwhi        Leidle "value=" false "/> <!--get a connection when test is valid-<property name=" Testonborrow "value=" false "/> <!--the test is valid when the connection is returned-<property name= "Testonreturn" value= "false"/> <!--open Pscache and specify p on each connection Scache Size--<property name= "Poolpreparedstatements" value= "false"/> <property name= "Maxpoolprep Aredstatementperconnectionsize "value="/> </bean>

The following is also in Applicationcontext.xml this configuration file, add Mybaits configuration (including things):
<!--mybatis sessionFaction 实例--><bean id="sqlSessionFaction" class="org.mybatis.spring.SqlSessionFactoryBean">    <property name="dataSource" ref="dataSource"/>    <!--mapper.xml 映射-->    <property name="mapperLocations" value="classpath:mapper/*.xml"/>    <!--pojo映射 , 这里映射到POJO包-->    <property name="typeAliasesPackage" value="com.graduation.pojo"/></bean><!-- DAO接口所在包名,Spring会自动查找其下的类 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">    <property name="basePackage" value="com.graduation.dao" /></bean><!--mybatis 事物配置--><bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    <property name="dataSource" ref="dataSource" /></bean><!-- 事务注解驱动,标注@Transactional的类和方法将具有事务性 --><tx:annotation-driven transaction-manager="txManager" />

Here's how to use the
Mybaits essential Mapper.xml, DAO, Pojo class. Here how to write the content of the landlord should be able to handle, to note that the path to the above configuration path to match. Similarly, these files can be automatically generated with Genertor.
Reference: Automatic generation of DAO, Model, mapping related files using Mybatis-generator (GO)-Master-Blog Park
It is also very easy to do interactive operations, and it is not necessary to be responsible for the life cycle of sessionfactory, and spring is in full charge.

Here is the test demo I generated through generator:
Pojo:
public class Test {private Long id;    private String test;    public Long getId() {return id;    }public void setId(Long id) {this.id = id;    }public String getTest() {return test;    }public void setTest(String test) {this.test = test == null ? null : test.trim();    }}

DAO:
// 这是我们Test类的dao层//这是spring的注解,有了它我们就可以通过spring的@Autowired实例化该类@Repositorypublic interface TestDao {    // 下面为CRUD操作    int deleteByPrimaryKey(Long id);       int insert(Test record);        int insertSelective(Test record);        Test selectByPrimaryKey(Long id);        int updateByPrimaryKeySelective(Test record);       int updateByPrimaryKey(Test record);}

Mapper.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.graduation.dao.TestMapper" > <resultmap id= "baseresultmap" type= " Com.graduation.domain.Test "> <id column=" id "property=" id "jdbctype=" BIGINT "/> <result column=" Test "p roperty= "Test" jdbctype= "VARCHAR"/> </resultMap> <sql id= "base_column_list" > ID, test</sql> & Lt;select id= "Selectbyprimarykey" resultmap= "Baseresultmap" parametertype= "Java.lang.Long" > select <include Refid= "Base_column_list"/> from test where id = #{id,jdbctype=bigint}</select> <delete id= "DeleteByPri Marykey "parametertype=" Java.lang.Long "> Delete from Test where id = #{id,jdbctype=bigint}</delete> <i Nsert id= "Insert" parametertype= "Com.graduation.domain.Test" > INSERT into Test (ID, test) VALUES (#{id,jdb Ctype=bigint},#{test,jdbctype=varchar}) </insert> <insert id= "insertselective" parametertype= " Com.graduation.domain.Test "> INSERT INTO Test<trim prefix=" ("suffix=") "suffixoverrides=", "> <if te    st= "id! = NULL" > id,</if> <if test= "Test! = null" > Test,</if> </trim> <trim prefix= "VALUES (" suffix= ")" suffixoverrides= "," > <if test= "id! = NULL" > #{id,jdbctype=b igint},</if> <if test= "Test! = null" > #{test,jdbctype=varchar},</if> </trim> < /insert> <update id= "updatebyprimarykeyselective" parametertype= "com.graduation.domain.Test" > Update test& Lt;set > <if test= "Test! = NULL" > test = #{test,jdbctype=varchar},</if> </set> whe Re id = #{id,jdbctype=bigint}</update> <update id= "Updatebyprimarykey" parametertype= " Com.graduation.domain.Test "> Update test set test = #{test,jdbctype=vArchar} WHERE id = #{id,jdbctype=bigint}</update></mapper> 

Then we run the demo from the test class (this cannot be tested by the main):
// 测试时候不能在main里面执行,因为main方法不会读取spring的配置文件@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"/spring-applicationContext.xml"})public class tets {    @Autowired    private TestDao testDao; // 这是我们的dao 不要被名字迷惑...        @Test    public void testSearchallUser() {        Test test = Test();        test.setTest("123");        testDao.insert(test) ;    }}
That's OK!

SPRINGMVC configuration and Spring configuration?

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.