当前位置:网站首页>Common configuration files of SSM framework

Common configuration files of SSM framework

2022-07-06 15:59:00 Star age Cao Botao

All say SSM Is the configuration factory , Here is the SSM The commonly used configuration files of the framework are sorted out for future development and use .

maven rely on

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <!--mysql drive -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>
        <!--ssm-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <!-- Database connection pool -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.4.RELEASE</version>
        </dependency>
        <!--aop Woven in bag -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>
        <!--junit unit testing -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
		<!--jackson-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.8</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>

JSP The file header

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--*****************************DAO*****************************-->
    <context:property-placeholder location="classpath:database.properties"/>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.botao.dao"/>
    </bean>
    <!--*****************************service*****************************-->
    <context:component-scan base-package="com.botao.service"/>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <aop:aspectj-autoproxy/>
</beans>

database.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/library?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

spring-mvc.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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--*****************************mvc*****************************-->
    <context:component-scan base-package="com.botao.controller"/>
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter" id="converter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <mvc:cors>
        <mvc:mapping path="/**" allowed-origins="*" allowed-methods="POST, GET, OPTIONS, DELETE, PUT" allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" allow-credentials="true"/>
    </mvc:cors>
    <mvc:default-servlet-handler/>
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--fileupload-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>
</beans>

MybatisUtil.java

package botao.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    
    private static SqlSessionFactory sqlSessionFactory;

    static {
    
        try {
    
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        } catch (IOException e) {
    
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession() {
    
        return sqlSessionFactory.openSession(false);
    }

    public static void close(SqlSession sqlSession) {
    
        sqlSession.close();
    }

}

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>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
 <typeAliases>
  <typeAlias alias="Author" type="domain.blog.Author"/>
  <package name="domain.blog"/>
</typeAliases>
  <mappers>
     <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
      <mapper url="file:///var/mappers/BlogMapper.xml"/>
      <mapper class="org.mybatis.builder.BlogMapper"/>
      <package name="org.mybatis.builder"/>
  </mappers>
</configuration>

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="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>

Set up (settings)

This is a MyBatis The most important adjustment settings in , They will change MyBatis Runtime behavior for . The following table describes the meaning of the settings in the settings 、 Default value, etc .

Set name describe Valid values The default value is
cacheEnabled Globally turn on or off any cache configured in all mapper profiles .true | falsetrue
lazyLoadingEnabled Global switch for delayed loading . When opened , All associated objects delay loading . You can set fetchType Property to override the on / off state of the item .true | falsefalse
aggressiveLazyLoading On , A call to any method loads all the deferred load properties of the object . otherwise , Each delay load property is loaded on demand ( Reference resources lazyLoadTriggerMethods).true | falsefalse ( stay 3.4.1 In previous versions, the default is true)
multipleResultSetsEnabled Whether to allow a single statement to return multiple result sets ( Need database driver support ).true | falsetrue
useColumnLabel Use column labels instead of column names . The actual performance depends on the database driver , For details, please refer to the relevant documents of database drive , Or through comparative tests to observe .true | falsetrue
useGeneratedKeys allow JDBC Support automatic generation of primary key , Need database driver support . If set to true, Automatic primary key generation will be enforced . Although some database drivers do not support this feature , But it still works ( Such as Derby).true | falseFalse
autoMappingBehavior Appoint MyBatis How should columns be automatically mapped to fields or properties . NONE Indicates that automatic mapping is turned off ;PARTIAL Only fields with no nested result mapping defined will be automatically mapped . FULL Will automatically map any complex result set ( Whether nested or not ).NONE, PARTIAL, FULLPARTIAL
autoMappingUnknownColumnBehavior Specify unknown column for discovery auto map target ( Or unknown property type ) act .NONE: No reaction WARNING: Output warning log ('org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' The log level of must be set to WARNFAILING: Mapping failed ( Throw out SqlSessionException)NONE, WARNING, FAILINGNONE
defaultExecutorType Configure default actuator .SIMPLE It's a common actuator ;REUSE The executor reuses the preprocessing statement (PreparedStatement); BATCH The executor not only reuses statements, but also performs batch updates .SIMPLE REUSE BATCHSIMPLE
defaultStatementTimeout Set timeout , It determines the number of seconds the database driver waits for a response from the database . Arbitrary positive integer Not set (null)
defaultFetchSize Get quantity for driven result set (fetchSize) Set a suggested value . This parameter can only be overridden in query settings . Arbitrary positive integer Not set (null)
defaultResultSetType Specifies the default scrolling strategy for the statement .( New at 3.5.2)FORWARD_ONLY | SCROLL_SENSITIVE | SCROLL_INSENSITIVE | DEFAULT( Equivalent to not set ) Not set (null)
safeRowBoundsEnabled Whether pagination is allowed in nested statements (RowBounds). Set to if allowed false.true | falseFalse
safeResultHandlerEnabled Whether result processors are allowed in nested statements (ResultHandler). Set to if allowed false.true | falseTrue
mapUnderscoreToCamelCase Whether to enable automatic mapping of hump naming , That is, from the classic database column name A_COLUMN Mapping to classic Java Property name aColumn.true | falseFalse
localCacheScopeMyBatis Using local caching mechanism (Local Cache) Prevent circular references and accelerate repeated nested queries . The default value is SESSION, All queries executed in a session are cached . If the setting is STATEMENT, The local cache will only be used to execute statements , Yes, the same SqlSession Will not be cached .SESSION | STATEMENTSESSION
jdbcTypeForNull When no specific... Is specified for the parameter JDBC Type , The default of null value JDBC type . Some database drivers need to specify columns of JDBC type , In most cases, just use the general type , such as NULL、VARCHAR or OTHER.JdbcType Constant , Common values :NULL、VARCHAR or OTHER.OTHER
lazyLoadTriggerMethods Specifies which methods of the object trigger a delayed load . Comma separated list of methods .equals,clone,hashCode,toString
defaultScriptingLanguage Designated dynamic SQL The default scripting language used in the build . A type alias or fully qualified class name .org.apache.ibatis.scripting.xmltags.XMLLanguageDriver
defaultEnumTypeHandler Appoint Enum Default for use TypeHandler .( New at 3.4.5) A type alias or fully qualified class name .org.apache.ibatis.type.EnumTypeHandler
callSettersOnNulls Specifies that when the result set value is null Whether to call the setter(map When object is put) Method , It depends on Map.keySet() or null Values are useful when initializing . Pay attention to basic types (int、boolean etc. ) Can't be set to null Of .true | falsefalse
returnInstanceForEmptyRow When all columns of the returned row are empty ,MyBatis Default return null. When this setting is turned on ,MyBatis An empty instance will be returned . Please note that , It also applies to nested result sets ( Such as a set or association ).( New at 3.4.2)true | falsefalse
logPrefix Appoint MyBatis Prefix added to log name . Any string Not set
logImpl Appoint MyBatis The implementation of the logs used , Auto find when not specified .SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING Not set
proxyFactory Appoint Mybatis The proxy tool used to create lazy load objects .CGLIB | JAVASSISTJAVASSIST (MyBatis 3.3 above )
vfsImpl Appoint VFS The implementation of the Customize VFS Class fully qualified name of , Separated by commas . Not set
useActualParamName Allow the name in the method signature as the statement parameter name . To use this feature , Your project must adopt Java 8 compile , And add -parameters Options .( New at 3.4.1)true | falsetrue
configurationFactory Specify a provider Configuration Instance classes . This one was returned Configuration Instance is used to load the value of the deferred load property of the deserialized object . This class must contain a signature of static Configuration getConfiguration() Methods .( New at 3.2.3) A type alias or fully qualified class name . Not set
shrinkWhitespacesInSql from SQL Delete the extra space characters in the . Please note that , It will also affect SQL Text string in . ( New at 3.5.5)true | falsefalse
defaultSqlProviderTypeSpecifies an sql provider class that holds provider method (Since 3.5.6). This class apply to the type(or value) attribute on sql provider annotation(e.g. @SelectProvider), when these attribute was omitted.A type alias or fully qualified class nameNot set

A fully configured settings An example of the element is as follows :

<settings>
  <setting name="cacheEnabled" value="true"/>
  <setting name="lazyLoadingEnabled" value="true"/>
  <setting name="multipleResultSetsEnabled" value="true"/>
  <setting name="useColumnLabel" value="true"/>
  <setting name="useGeneratedKeys" value="false"/>
  <setting name="autoMappingBehavior" value="PARTIAL"/>
  <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
  <setting name="defaultExecutorType" value="SIMPLE"/>
  <setting name="defaultStatementTimeout" value="25"/>
  <setting name="defaultFetchSize" value="100"/>
  <setting name="safeRowBoundsEnabled" value="false"/>
  <setting name="mapUnderscoreToCamelCase" value="false"/>
  <setting name="localCacheScope" value="SESSION"/>
  <setting name="jdbcTypeForNull" value="OTHER"/>
  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>

select

<select id="selectPerson" parameterType="int" parameterMap="deprecated" resultType="hashmap" resultMap="personResultMap" flushCache="false" useCache="true" timeout="10" fetchSize="256" statementType="PREPARED" resultSetType="FORWARD_ONLY">
attribute describe
id Unique identifier in namespace , Can be used to refer to this statement .
parameterType The class fully qualified name or alias of the parameter that will be passed into this statement . This property is optional , because MyBatis You can use the type processor (TypeHandler) Infer the parameters of the specific incoming statement , Default is not set (unset).
parameterMap Used to reference external parameterMap Properties of , It is now abandoned . Use inline parameter mapping and parameterType attribute .
resultType The fully qualified name or alias of the class expected to return the result from this statement . Be careful , If you are returning a collection , That should be set to the type the collection contains , Rather than the type of the collection itself . resultType and resultMap Only one can be used at the same time .
resultMap To the outside resultMap A named reference to . The resulting mapping is MyBatis The most powerful feature , If you understand it thoroughly , Many complex mapping problems can be solved easily . resultType and resultMap Only one can be used at the same time .
flushCache Set it to true after , As long as the statement is called , Both the local cache and the secondary cache will be emptied , The default value is :false.
useCache Set it to true after , The result of this statement will be cached by the second level cache , The default value is : Yes select Element is true.
timeout This setting is before throwing an exception , The number of seconds the driver waits for the database to return the result of the request . Default is not set (unset)( Rely on the database driver ).
fetchSize This is a recommended value for the driver , Try to make the number of rows returned by the driver in batches equal to this setting . Default is not set (unset)( Dependency driven ).
statementType Optional STATEMENT,PREPARED or CALLABLE. It will make MyBatis Separate use Statement,PreparedStatement or CallableStatement, The default value is :PREPARED.
resultSetTypeFORWARD_ONLY,SCROLL_SENSITIVE, SCROLL_INSENSITIVE or DEFAULT( Equivalent to unset) One of them , The default value is unset ( Rely on the database driver ).
databaseId If the database vendor ID is configured (databaseIdProvider),MyBatis Will load all without databaseId Or match the current databaseId The sentence of ; If there are sentences with and without , What you don't bring will be ignored .
resultOrdered This setting is only for nested results select sentence : If true, It is assumed that nested result sets or groups are included , When a main result row is returned , There is no reference to the previous result set . This makes it possible to get nested result sets without running out of memory . The default value is :false.
resultSets This setting only applies to multiple result sets . It will list the result sets returned after the statement is executed and give each result set a name , Multiple names are separated by commas .

insert, update , delete

Data change statement insert,update and delete The implementation of is very close to :

<insert id="insertAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" keyProperty="" keyColumn="" useGeneratedKeys="" timeout="20">

<update id="updateAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" timeout="20">

<delete id="deleteAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" timeout="20">
attribute describe
id Unique identifier in namespace , Can be used to refer to this statement .
parameterType The class fully qualified name or alias of the parameter that will be passed into this statement . This property is optional , because MyBatis You can use the type processor (TypeHandler) Infer the parameters of the specific incoming statement , Default is not set (unset).
parameterMap Used to reference external parameterMap Properties of , It is now abandoned . Use inline parameter mapping and parameterType attribute .
flushCache Set it to true after , As long as the statement is called , Both the local cache and the secondary cache will be emptied , The default value is :( Yes insert、update and delete sentence )true.
timeout This setting is before throwing an exception , The number of seconds the driver waits for the database to return the result of the request . Default is not set (unset)( Rely on the database driver ).
statementType Optional STATEMENT,PREPARED or CALLABLE. It will make MyBatis Separate use Statement,PreparedStatement or CallableStatement, The default value is :PREPARED.
useGeneratedKeys( Only applicable to insert and update) This will make MyBatis Use JDBC Of getGeneratedKeys Method to retrieve the primary key generated inside the database ( such as : image MySQL and SQL Server Such a relational database management system automatically incremental fields ), The default value is :false.
keyProperty( Only applicable to insert and update) Specify properties that uniquely recognize the object ,MyBatis Will use getGeneratedKeys Or insert Of the statement selectKey The child element sets its value , The default value is : Not set (unset). If you generate more than one column , Multiple attribute names can be separated by commas .
keyColumn( Only applicable to insert and update) Set the column name of the generated key value in the table , In some databases ( image PostgreSQL) in , When the primary key column is not the first column in the table , It must be set . If you generate more than one column , Multiple attribute names can be separated by commas .
databaseId If the database vendor ID is configured (databaseIdProvider),MyBatis Will load all without databaseId Or match the current databaseId The sentence of ; If there are sentences with and without , What you don't bring will be ignored .

dynamic sql

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
        #{item}
  </foreach>
</select>
<!-- Batch insert -->
<insert id="mAdd" parameterType="list">
        insert into student (id, name, sex, card, phone, department, banji, banjiid)
        values
        <foreach collection="list" separator="," item="stu">
            (#{stu.id}, #{stu.name}, #{stu.sex}, #{stu.card}, #{stu.phone}, #{stu.department}, #{stu.banji},1)
        </foreach>
</insert>
<!-- Batch update mysql Batch update settings need to be enabled allowMultiQueries=true-->
<update id="mUpdate" parameterType="java.util.List">
        <foreach collection="list" item="stu">
            update student
            <set>
                <if test="stu.name!=null">
                    name = #{stu.name},
                </if>
                <if test="stu.sex!=null">
                    sex = #{stu.sex},
                </if>
                <if test="stu.card!=null">
                    card = #{stu.card},
                </if>
                <if test="stu.phone!=null">
                    phone = #{stu.phone},
                </if>
                <if test="stu.department!=null">
                    department = #{stu.department},
                </if>
                <if test="stu.banji!=null">
                    banji = #{stu.banji},
                </if>
            </set>
            where id = #{stu.id};
        </foreach>
</update>
<!--bind Fuzzy query -->
<select id="queryLikebanji" resultType="top.scsoul.mybatis.pojo.Student">
            <bind name="banji" value="'%'+banji+'%'"/>
            select * from student where banji like #{banji};
</select>

Association mapping

Two labels

one-on-one association

One to many collection

Two ways

nested queries

Nesting results

<?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">
<!--suppress SqlNoDataSourceInspection -->
<mapper namespace="com.botao.mapper.UserMapper">
    <!-- Nesting results -->
    <resultMap id="getUserByIdRm" type="com.botao.pojo.User">
        <id property="id" column="user_id"/>
        <result property="username" column="user_name"/>
        <association property="cadId" column="user_card_id" javaType="com.botao.pojo.Card">
            <id property="id" column="dbcardId"/>
            <result property="createdBy" column="created_by"/>
        </association>
        <collection property="orders" ofType="order" javaType="list">
            <id property="id" column="order_id"/>
            <result property="name" column="order_name"/>
        </collection>
    </resultMap>
    <select id="getUserById" parameterType="int" resultMap="getUserByIdRm">
        select user.*, card.card_id as dbcardId, card.created_by, o.order_id, o.order_name
        from user
                 join card on card.card_id = user.user_card_id
                 join `order` as o on user.user_id = o.user_id
        where user.user_id = #{id};
    </select>
	<!-- nested queries -->
    <resultMap id="getUserByIdRm2" type="com.botao.pojo.User">
        <id property="id" column="user_id"/>
        <result property="username" column="user_name"/>
        <association property="cadId" column="user_card_id" select="com.botao.mapper.CardMapper.getCard">
        </association>
        <collection property="orders" ofType="com.botao.pojo.Order" column="user_id" select="com.botao.mapper.OrderMapper.getOrderByUserId">
        </collection>
    </resultMap>
    <select id="getUserById2" parameterType="int" resultMap="getUserByIdRm2">
        select user_id,user_name,user_card_id
        from user
        where user_id = #{id};
    </select>

</mapper>

tip: Try to use join More efficient .

原网站

版权声明
本文为[Star age Cao Botao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060919408118.html