MyBatis之注解开发-yellowcong

MyBatis 专栏收录该内容
4 篇文章 0 订阅

Mybatisy的对象映射的时候,只能名称一一对应,才可以映射上,不然就需要通过@Results来设定别名,同时在传递多个参数的时候,需要通过@Param来指定对应的参数,我本人觉得基于注解开发相对于XML更加的舒服一些。

常用注解

CURD过程中,实际上是根据注解,来判断PreparedStatement使用executeUpdate还是executeQuery

注解意义
@Delete删除
@Select查询
@Update更新
@Insert数据插入
@Results和@Result用来解决数据库字段和实体类名称不一致
@Param多个参数的情况,需要指定参数名称
@Options(useGeneratedKeys = true, keyProperty = “studId”)注解的userGeneratedKeys和keyProperty属性让数据库产生 auto_increment(自增长)列的值,然后将生成的值设置到输入参数对象的属性中。
@SelectKey@SelectKey来生成主键值,并且存储到了要插入的数据属性上。由于我们设置了before=true,该语句将会在执行INSERT语句之前执行

例子

获取主键

我们可以使用 @SelectKey注解来为任意SQL语句来指定主键值,作为主键列的值。假设我们有一个名为STUD_ID_SEQ的序列来生成STUD_ID主键值。
这里我们使用了 @SelectKey来生成主键值,并且存储到了student对象的studId属性上。由于我们设置了before=true,该语句将会在执行INSERT语句之前执行

@Insert("insert into students(stud_id,name,email,addr_id,phone) values(#{studId},#{name},#{email},#{address.addrId},#{phone})")  
@SelectKey(statement="select my_seq.nextval from dual", keyProperty="studId", resultType=int.class, before=true)  
int insertStudent(Student student);  

自动生成主键

可以使用 @Options注解的userGeneratedKeys和keyProperty属性让数据库产生 auto_increment(自增长)列的值,然后将生成的值设置到输入参数对象的属

@Insert("insert into students(name,email,addr_id, phone) values(#{name},#{email},#{address.addr Id},#{phone})")
int insertStudent(Student student);

@Options(useGeneratedKeys = true, keyProperty = “studId”) 这里STUD_ID列值将会通过MySQL数据库自动生成。并且生成的值将会被设置到student对象的studId属性中。

案例

数据库

CREATE TABLE `yellowcong_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `age` int(11) DEFAULT NULL,
  `nick_name` varchar(32) DEFAULT NULL,
  `password` varchar(32) DEFAULT NULL,
  `user_name` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

dao

package com.yellowcong.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.yellowcong.entity.User;

/**
*
*作者:yellowcong
*日期:2017/11/23
*時間:15:55:25
*描述:
*/
public interface UserDao {

    //插入数据
    @Insert("INSERT INTO YELLOWCONG_USERS VALUES (null,#{age},#{nickName},#{password},#{userName})")
    void addUser(User user);

    //查询某个字段
    @Select("SELECT * FROM YELLOWCONG_USERS WHERE USER_NAME = #{username}")
    //修改别名的问题
    @Results({  
        @Result(column = "nick_name", property = "nickName"),  
        @Result(column = "user_name", property = "userName"),  
    })
    User getUser(String username);

    //更新操作
    //多个参数的情况,需要设置@Param ,指定参数
    //只有一个的情况,就不需要指定了
    @Update("UPDATE YELLOWCONG_USERS SET password =#{password} WHERE user_name = #{user_name}")
    void updateUser(@Param("user_name")String userName,@Param("password")String password );


    //删除数据
    @Delete("DELETE FROM YELLOWCONG_USERS WHERE USER_NAME = #{username} ")
    void delete(String username);

    @Select("SELECT * FROM YELLOWCONG_USERS")
    //修改别名的问题
    @Results({  
        @Result(column = "nick_name", property = "nickName"),  
        @Result(column = "user_name", property = "userName"),  
    })
    List<User> getAllUser();

}

entity

package com.yellowcong.entity;

/**
 *
 * 作者:yellowcong 日期:2017/11/23 時間:16:03:39 描述:
 */
public class User {
    private Integer id;
    private Integer age;
    private String nickName;
    private String password;
    private String userName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

测试类

package com.yellowcong.dao;

import java.util.List;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.yellowcong.entity.User;

/**
*
*作者:yellowcong
*日期:2017/11/23
*時間:16:06:28
*描述:
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class UserDaoTest {
    @Autowired
    private UserDao userDao;
    private static String username ;

    @Before
    public void setUp() {
        username = "test";
    }
    @Test
    public void testAdd() {
        User user = new User();
        user.setAge(1314);
        user.setNickName("doubi");
        user.setPassword("xxx");
        user.setUserName(username);
        this.userDao.addUser(user);
    }

    @Test
    public void testList() {
        List<User> users = userDao.getAllUser();
        Assert.assertTrue(users.size()>0);
    }

    @Test
    public void testLoad() {
        User user = this.userDao.getUser(username);
        Assert.assertEquals(username, user.getUserName());
    }

    @Test
    public void testUpdateUser() {
        String password = "password";
        this.userDao.updateUser(username,password);

        User user = this.userDao.getUser(username);
        Assert.assertEquals(password, user.getPassword());
    }

    @Test
    public void testDelete() {
        this.userDao.delete(username);
        User user = this.userDao.getUser(username);
        Assert.assertNull(user);
    }
}

环境搭建

目录结构

这里写图片描述

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>yellowcong</groupId>
    <artifactId>day11_23</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>day11_23 Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <!-- 配置国内比较快的 阿里云的Maven仓库 -->
    <repositories>
        <repository>
            <id>aliyunmaven</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        </repository>
    </repositories> <!-- 共用的配置说明,比如spring版本, 项目名称, jdk版本等 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.2.5.RELEASE</spring.version>
    </properties>
    <dependencies> <!-- Spring BEGIN -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency> <!-- 导入Spring的orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency> <!-- Slf4j -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency> <!-- 配置切面 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency> <!---aspectj 面向切向 -->
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.5</version>
        </dependency> <!-- Spring需要的注解 -->
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.2</version>
        </dependency> <!-- Spring 的测试类 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency> <!-- Spring END --> <!-- 配置Spring mvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency> 
        <!-- 文件上传 Begin -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency> 
        <!-- 文件上传 End -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency> <!-- JSON解析 -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.11</version>
        </dependency> 
        <!-- 日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <!-- slf4j的代码 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.2</version>
        </dependency>

        <!-- ################################################ -->
        <!-- ########### 数据库配置 BEGIN     ###################-->
        <!-- ################################################ -->

        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.1.1</version>
        </dependency>

        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.18</version>
        </dependency>
        <!-- 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>

        <!-- ################################################ -->
        <!-- ########### 数据库配置 END       ###################-->
        <!-- ################################################ -->

    </dependencies>
    <build>
        <finalName>day11_23</finalName>
    </build>
</project>

web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>demo</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list> <!-- Spring mvc -->
    <servlet>
        <servlet-name>config</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置Spring mvc,如果不配置,就会默认在wWEB-INF/config-servlet.xml -->
        <init-param>
            <description>spring mvc 配置文件</description>
            <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>config</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping> 
    <!-- 设定字符编码 -->
    <filter>
        <filter-name>CharacterFilter</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>CharacterFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping> 
    <!-- spring的监听器,可以通过上下文来获取参数 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>
</web-app>

spring.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:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-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/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    "> 
    <!-- 自动扫描(自动注入) -->
    <context:annotation-config />
    <context:component-scan base-package="com.yellowcong.*" /> 


     <!-- 引入属性文件 -->
     <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <!-- 除了支持配置的properties文件外,还支持系统属性
        SYSTEM_PROPERTIES_MODE_OVERRIDE   //系统属性可以被覆盖
        SYSTEM_PROPERTIES_MODE_NEVER  //不检测系统属性
        SYSTEM_PROPERTIES_MODE_FALLBACK  // 这个是默认的配置
        -->
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> 
        <!-- 里面配置的properties文件如果找不到的话,就可以忽略找不到的文件 -->
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean> 

    <!--导入mybatis的配置 -->
    <import resource="spring-mybatis.xml"/> 
      <!-- <import resource="spring-shiro.xml"/> -->
     <import resource="spring-mvc.xml"/>

</beans>

spring-mybatis.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.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/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
            >
    <!-- 自动扫描(自动注入) -->
    <context:annotation-config/>
    <context:component-scan base-package="com.yellowcong.service.impl.*"/>

    <!-- 配置日志输出 -->
    <bean id="log-filter" class="com.alibaba.druid.filter.logging.Log4jFilter">
        <property name="statementExecutableSqlLogEnable" value="true" />
    </bean>

    <!-- 配置数据源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" /> 
        <property name="url" value="${jdbc.url}" /> 
        <property name="username" value="${jdbc.username}" /> 
        <property name="password" value="${jdbc.password}" /> 
        <property name="initialSize" value="${jdbc.initialSize}" /> 
        <property name="minIdle" value="${jdbc.minIdle}" /> 
        <property name="maxActive" value="${jdbc.maxActive}" /> 
        <property name="maxWait" value="${jdbc.maxWait}" /> 
        <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" /> 
        <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" /> 
        <property name="validationQuery" value="${jdbc.validationQuery}" /> 
        <property name="testWhileIdle" value="${jdbc.testWhileIdle}" /> 
        <property name="testOnBorrow" value="${jdbc.testOnBorrow}" /> 
        <property name="testOnReturn" value="${jdbc.testOnReturn}" /> 
        <property name="removeAbandoned" value="${jdbc.removeAbandoned}" /> 
        <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" /> 
       <!--  <property name="logAbandoned" value="${jdbc.logAbandoned}" />  -->
        <property name="filters" value="${jdbc.filters}" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true" />
        <property name="proxyFilters">
            <list>
                <ref bean="log-filter"/>
            </list>
        </property>

        <!-- 监控数据库 -->
        <!-- <property name="filters" value="stat" /> -->
<!--        <property name="filters" value="mergeStat" />-->
    </bean>

    <!-- 配置Session factory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations"  >
            <list>
                <value>classpath*:com/yellowcong/mapper/*.xml</value>
            </list>
        </property>
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>

    <!--这个是定义的一个Base的操作类 -->
    <!-- <bean id="baseMybatisDao" class="com.yellowcong.core.mybatis.BaseMybatisDao" >
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>  -->

    <!-- 定义用户的Dao的位置 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 定义我们需要查找的Dao的位置 --> 
        <property name="basePackage" value="com.yellowcong.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!-- 事物管理 -->
     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         <property name="dataSource" ref="dataSource" />
     </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="publish*" />
            <tx:method name="save*" />
            <tx:method name="add*" />
            <tx:method name="update*" />
            <tx:method name="insert*" />
            <tx:method name="create*" />
            <tx:method name="del*" />
            <tx:method name="load*" />
            <tx:method name="init*" />
            <tx:method name="*"  read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- AOP配置,设定织入的位置--> 
    <aop:config>
        <aop:pointcut id="dbPointcut"
            expression="execution(public * com.yellowcong.*.service.impl.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="dbPointcut" />
    </aop:config>
</beans>

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>

  <settings>        
    <setting name="defaultExecutorType" value="REUSE" />
  </settings>

  <typeAliases>

  </typeAliases>

 <!-- 
 <mappers>
    <mapper resource="mapper/StudentMapper.xml"/>
 </mappers>
    <plugins>  
       <plugin interceptor="net.wenyifan.common.mybatis.plugin.PageInterceptor">    
       </plugin>  
    </plugins>    
-->
</configuration>

jdbc.properties

#Defined jdbc config
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///yellowcong
jdbc.username=root
jdbc.password=root
jdbc.initialSize=3 
jdbc.minIdle=2
jdbc.maxActive=60
jdbc.maxWait=60000
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=30000
jdbc.validationQuery=SELECT 'x'
jdbc.testWhileIdle=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false
jdbc.poolPreparedStatements=true
jdbc.maxPoolPreparedStatementPerConnectionSize=20
jdbc.removeAbandoned=true
jdbc.removeAbandonedTimeout=120
jdbc.logAbandoned=false
jdbc.filters=stat

log4j.properties

log4j.rootLogger=WARN, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
#log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
# Print the date in ISO 8601 format
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
# Print only messages of level WARN or above in the package com.foo.
log4j.logger.com.yellowcong=WARN

# mybatis log
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG


spring-mvc.xml

这个是spring mvc,都贴上来,这个也就贴上来吧

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.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-3.1.xsd">
    <mvc:default-servlet-handler />
     <!-- 通过Annotation 来控制Controller -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <context:component-scan base-package="com.yellowcong.*"/> 

    <!-- 将静态文件夹制定到某个特别的文件夹中统一处理 ** 表示的是文件夹中的子文件夹中的所有类容 其中location 需要两个 正斜杠 -->
    <mvc:resources location="/resources/" mapping="/resources/**" />

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
        <!-- 最大文件大小,-1为无限止(-1) -->
        <property name="maxUploadSize" value="5000000" /> 
        <!-- 最大内存大小 (10240) -->
        <property name="maxInMemorySize" value="10240" /> 
        <!-- 设置编码 ,默认编码 (ISO-8859-1) -->
        <property name="defaultEncoding" value="UTF-8" /> 
        <!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常 -->
        <property name="resolveLazily" value="true" />
    </bean>
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView"></property> 
        <property name="prefix" value="/WEB-INF/jsp/"></property> 
        <property name="suffix" value=".jsp"></property>
    </bean>
    <bean
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props> 
            </props>
        </property>
    </bean>
</beans>

常见问题

多参数需指定别名

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'password' not found. Available parameters are [0, 1, param1, param2]
    at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:73)
    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:365)

这里写图片描述

经测试应该是忘了使用@Param。当只有一个参数时,Mapper中可以不使用

@Delete("DELETE FROM YELLOWCONG_USERS WHERE USER_NAME = #{username} ")
int delete(String username);

但是有多个参数时必须用:

@Update("UPDATE YELLOWCONG_USERS SET password =#{password} WHERE user_name = #{user_name}")
int updateUser(@Param("user_name")String userName,@Param("password")String password );

参考文章

https://www.cnblogs.com/saule/articles/6127736.html
http://blog.csdn.net/suwu150/article/details/52896496

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值