zoukankan      html  css  js  c++  java
  • eclipse搭建ssm框架

    新建数据库ssm

    建立数据库表user

    CREATE TABLE `user` (
      `id` int(11) NOT NULL AUTO_INCREMENT ,
      `sex` varchar(255) NULL ,
      `name` varchar(255) NULL ,
      PRIMARY KEY (`id`)
    );

    新建一个Java web工程 SSM,目录结构如下

    下面挨个看下配置文件

    conf.properties配置详情

    url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    driver=com.mysql.jdbc.Driver
    username=root
    password=root
    

    log4j.properties配置详情

    log4j.rootLogger=info, live, file
    log4j.logger.org.springframework=ERROR
    —log4j.logger.org.logicalcobwebs.proxool=ERROR 
    log4j.appender.live=org.apache.log4j.ConsoleAppender
    log4j.appender.live.Target=System.out
    log4j.appender.live.layout=org.apache.log4j.PatternLayout
    log4j.appender.live.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss}(%r)%n--> [%t] %l: %m %x %n
    log4j.appender.file.File=/log/liveApi.log
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.file.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss}(%r)%n--> [%t] %l: %m %x %n
    log4j.appender.file.DatePattern='.'yyyy-MM-dd'.log'
    log4j.logger.com.ssm.dao=DEBUG

    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"
    	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>
    	<welcome-file-list>
    		<welcome-file>index.html</welcome-file>
    		<welcome-file>index.htm</welcome-file>
    		<welcome-file>index.jsp</welcome-file>
    		<welcome-file>default.html</welcome-file>
    		<welcome-file>default.htm</welcome-file>
    		<welcome-file>default.jsp</welcome-file>
    	</welcome-file-list>
    	<!-- 配置 Spring -->
    	<context-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>/WEB-INF/applicationContext.xml</param-value>
    	</context-param>
    	<!-- 配置DispatchcerServlet -->
    	<servlet>
    		<servlet-name>springDispatcherServlet</servlet-name>
    		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    		<!-- 配置Spring mvc下的配置文件的位置和名称 -->
    		<init-param>
    			<param-name>contextConfigLocation</param-name>
    			<param-value>/WEB-INF/springmvc.xml</param-value>
    		</init-param>
    
    		<load-on-startup>1</load-on-startup>
    	</servlet>
    	<servlet-mapping>
    		<servlet-name>springDispatcherServlet</servlet-name>
    		<url-pattern>/</url-pattern>
    	</servlet-mapping>
    	<!-- spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter用于解决POST方式造成的中文乱码问题 -->
    	<filter>
    		<filter-name>encodingFilter</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>
    		<!-- force强制,促使 -->
    		<init-param>
    			<param-name>forceEncoding</param-name>
    			<param-value>true</param-value>
    		</init-param>
    	</filter>
    	<filter-mapping>
    		<filter-name>encodingFilter</filter-name>
    		<url-pattern>/</url-pattern>
    	</filter-mapping>
    	<!-- Spring监听器 -->
    	<listener>
    		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    	</listener>
    	<!-- 防止Spring内存溢出监听器 -->
    	<listener>
    		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    	</listener>
    	<!-- 异常页面捕获 -->
    	<error-page>
    		<exception-type>java.lang.Throwable</exception-type>
    		<location>/500.html</location>
    	</error-page>
    	<error-page>
    		<error-code>500</error-code>
    		<location>/500.html</location>
    	</error-page>
    	<error-page>
    		<error-code>404</error-code>
    		<location>/404.html</location>
    	</error-page>
    </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:mvc="http://www.springframework.org/schema/mvc"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans   
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
                http://www.springframework.org/schema/mvc   
                http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
                http://www.springframework.org/schema/context   
                http://www.springframework.org/schema/context/spring-context-3.0.xsd   
                http://www.springframework.org/schema/aop   
                http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
                http://www.springframework.org/schema/tx   
                http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
    
    	<!-- 配置自动扫描的包 -->
    	<context:component-scan base-package="com.ssm">
    		<!-- 制定扫包规则 ,扫描除去使用@Controller注解的JAVA类 -->
    		<context:exclude-filter type="annotation"
    			expression="org.springframework.stereotype.Controller" />
    	</context:component-scan>
    
    	<!-- ===========================数据源配置=============================== -->
    	<!-- 引入外部数据源配置信息 -->
    	<bean
    		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    		<property name="locations">
    			<value>classpath:conf.properties</value>
    		</property>
    	</bean>
    
    	<!-- 配置数据源 -->
    	<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
    		init-method="init" destroy-method="close">
    		<property name="driverClassName" value="${driver}" />
    		<property name="url" value="${url}" />
    		<property name="username" value="${username}" />
    		<property name="password" value="${password}" />
    		<!-- 初始化连接大小 -->
    		<property name="initialSize" value="0" />
    		<!-- 连接池最大使用连接数量 -->
    		<property name="maxActive" value="20" />
    		<!-- 连接池最小空闲 -->
    		<property name="minIdle" value="0" />
    		<!-- 获取连接最大等待时间 -->
    		<property name="maxWait" value="60000" />
    
    		<property name="validationQuery">
    			<value>SELECT 1</value>
    		</property>
    		<property name="testOnBorrow" value="false" />
    		<property name="testOnReturn" value="false" />
    		<property name="testWhileIdle" value="true" />
    
    		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
    		<property name="timeBetweenEvictionRunsMillis" value="60000" />
    		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
    		<property name="minEvictableIdleTimeMillis" value="25200000" />
    
    		<!-- 打开removeAbandoned功能 -->
    		<property name="removeAbandoned" value="true" />
    		<!-- 1800秒,也就是30分钟 -->
    		<property name="removeAbandonedTimeout" value="1800" />
    		<!-- 关闭abanded连接时输出错误日志 -->
    		<property name="logAbandoned" value="true" />
    
    		<!-- 监控数据库 -->
    		<!-- <property name="filters" value="stat" /> -->
    		<property name="filters" value="mergeStat" />
    	</bean>
    	<!-- 配置MyBatis session工厂 -->
    	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    		<property name="dataSource" ref="dataSource" />
    		<!-- 自动扫描mapping.xml文件 -->
    		<property name="mapperLocations" value="classpath:com/ssm/mapper/*.xml"></property>
    	</bean>
    
    	<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    		<property name="basePackage" value="com.ssm.dao" />
    		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    	</bean>
    
    	<!-- (事务管理)transaction manager -->
    	<bean id="transactionManager"
    		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    		<property name="dataSource" ref="dataSource" />
    	</bean>
    
    	<!-- 注解方式配置事物 -->
    	<tx:annotation-driven transaction-manager="transactionManager" />
    
    </beans>

    springmvc.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:tx="http://www.springframework.org/schema/tx"
    	xmlns:task="http://www.springframework.org/schema/task"
    	xsi:schemaLocation="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-4.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
                http://www.springframework.org/schema/tx   
            http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
             http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
         ">
    	<!-- ====================================================== -->
    	<!-- 配置@ResponseBody 保证返回值为UTF-8 -->
    	<!-- 因为StringHttpMessageConverter默认是ISO8859-1 -->
    	<!-- 用于使用@ResponseBody后返回中文避免乱码 -->
    	<bean id="utf8Charset" class="java.nio.charset.Charset"
    		factory-method="forName">
    		<constructor-arg value="UTF-8" />
    	</bean>
    
    	<!-- 配置自动扫描的包 -->
    	<context:component-scan base-package="com.ssm">
    		<!-- 制定扫包规则 ,只扫描使用@Controller注解的JAVA类 -->
    		<context:include-filter type="annotation"
    			expression="org.springframework.stereotype.Controller" />
    	</context:component-scan>
    
    	<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    	<mvc:annotation-driven>
    		<mvc:message-converters register-defaults="true">
    			<!-- 配置Fastjson支持 -->
    			<bean
    				class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
    				<property name="charset" value="UTF-8" />
    				<property name="supportedMediaTypes">
    					<list>
    						<value>text/html;charset=UTF-8</value>
    						<value>application/json</value>
    						<value>application/xml;charset=UTF-8</value>
    					</list>
    				</property>
    				<property name="features">
    					<list>
    						<!-- 输出key时是否使用双引号 -->
    						<value>QuoteFieldNames</value>
    						<!-- 是否输出值为null的字段 -->
    						<!-- <value>WriteMapNullValue</value> -->
    						<!-- 数值字段如果为null,输出为0,而非null -->
    						<value>WriteNullNumberAsZero</value>
    						<!-- List字段如果为null,输出为[],而非null -->
    						<value>WriteNullListAsEmpty</value>
    						<!-- 字符类型字段如果为null,输出为"",而非null -->
    						<value>WriteNullStringAsEmpty</value>
    						<!-- Boolean字段如果为null,输出为false,而非null -->
    						<value>WriteNullBooleanAsFalse</value>
    						<!-- null String不输出 -->
    						<value>WriteNullStringAsEmpty</value>
    						<!-- null String也要输出 -->
    						<!-- <value>WriteMapNullValue</value> -->
    
    						<!-- Date的日期转换器 -->
    						<value>WriteDateUseDateFormat</value>
    					</list>
    				</property>
    			</bean>
    		</mvc:message-converters>
    	</mvc:annotation-driven>
    
    	<!-- 文件上传配置 -->
    	<bean id="multipartResolver"
    		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    		<property name="defaultEncoding">
    			<value>UTF-8</value>
    		</property>
    		<property name="maxUploadSize">
    			<!-- 100M 1024 * 1024 * 100 -->
    			<value>104857600</value>
    		</property>
    		<property name="maxInMemorySize">
    			<value>4096</value>
    		</property>
    	</bean>
    </beans>
    

    ==============顺便介绍一下数据库逆向生成工具(网上应该也有现成的)================================start

    新建一个java 工程generatorSqlmapCustom,如下图所示

    generatorConfig.xml配置详情

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE generatorConfiguration
      PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
      "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    
    <generatorConfiguration>
    	<context id="testTables" targetRuntime="MyBatis3">
    		<commentGenerator>
    			<!-- 是否去除自动生成的注释 true:是 : false:否 -->
    			<property name="suppressAllComments" value="true" />
    		</commentGenerator>
    		<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
    		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
    			connectionURL="jdbc:mysql://localhost:3306/ssm" userId="root"
    			password="root">
    		</jdbcConnection>
    		<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 
    			NUMERIC 类型解析为java.math.BigDecimal -->
    		<javaTypeResolver>
    			<property name="forceBigDecimals" value="false" />
    		</javaTypeResolver>
    
    		<!-- targetProject:生成PO类的位置 -->
    		<javaModelGenerator targetPackage="com.ssm.pojo"
    			targetProject=".src">
    			<!-- enableSubPackages:是否让schema作为包的后缀 -->
    			<property name="enableSubPackages" value="false" />
    			<!-- 从数据库返回的值被清理前后的空格 -->
    			<property name="trimStrings" value="true" />
    		</javaModelGenerator>
            <!-- targetProject:mapper映射文件生成的位置 -->
    		<sqlMapGenerator targetPackage="com.ssm.dao" 
    			targetProject=".src">
    			<!-- enableSubPackages:是否让schema作为包的后缀 -->
    			<property name="enableSubPackages" value="false" />
    		</sqlMapGenerator>
    		<!-- targetPackage:mapper接口生成的位置 -->
    		<javaClientGenerator type="XMLMAPPER"
    			targetPackage="com.ssm.dao" 
    			targetProject=".src">
    			<!-- enableSubPackages:是否让schema作为包的后缀 -->
    			<property name="enableSubPackages" value="false" />
    		</javaClientGenerator>
    		<!-- 指定数据库表 -->
    		<table schema="" tableName="user"></table>
    	</context>
    </generatorConfiguration>
    

    GeneratorSqlmap.java代码

    public void generator() throws Exception{
    
    		List<String> warnings = new ArrayList<String>();
    		boolean overwrite = true;
    		//指定 逆向工程配置文件
    		File configFile = new File("generatorConfig.xml"); 
    		ConfigurationParser cp = new ConfigurationParser(warnings);
    		Configuration config = cp.parseConfiguration(configFile);
    		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
    		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
    				callback, warnings);
    		myBatisGenerator.generate(null);
    
    	} 
    	public static void main(String[] args) throws Exception {
    		try {
    			GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
    			generatorSqlmap.generator();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	
    		
    	}

    执行main函数 生成对应的映射文件,然后刷新项目

    ==============顺便介绍一下数据库逆向生成工具================================end

     将逆向生成的文件拷贝到对应的文件夹

     

    如果不想使用逆向工程,手动配置一下也可以

    User.java

    package com.ssm.pojo;
    
    public class User {
        private Integer id;
    
        private String sex;
    
        private String name;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex == null ? null : sex.trim();
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name == null ? null : name.trim();
        }
    }
    

    UserExample.java其实这个类可以没有,这个类主要就是方便配置sql查询条件

    package com.ssm.pojo;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class UserExample {
        protected String orderByClause;
    
        protected boolean distinct;
    
        protected List<Criteria> oredCriteria;
    
        public UserExample() {
            oredCriteria = new ArrayList<Criteria>();
        }
    
        public void setOrderByClause(String orderByClause) {
            this.orderByClause = orderByClause;
        }
    
        public String getOrderByClause() {
            return orderByClause;
        }
    
        public void setDistinct(boolean distinct) {
            this.distinct = distinct;
        }
    
        public boolean isDistinct() {
            return distinct;
        }
    
        public List<Criteria> getOredCriteria() {
            return oredCriteria;
        }
    
        public void or(Criteria criteria) {
            oredCriteria.add(criteria);
        }
    
        public Criteria or() {
            Criteria criteria = createCriteriaInternal();
            oredCriteria.add(criteria);
            return criteria;
        }
    
        public Criteria createCriteria() {
            Criteria criteria = createCriteriaInternal();
            if (oredCriteria.size() == 0) {
                oredCriteria.add(criteria);
            }
            return criteria;
        }
    
        protected Criteria createCriteriaInternal() {
            Criteria criteria = new Criteria();
            return criteria;
        }
    
        public void clear() {
            oredCriteria.clear();
            orderByClause = null;
            distinct = false;
        }
    
        protected abstract static class GeneratedCriteria {
            protected List<Criterion> criteria;
    
            protected GeneratedCriteria() {
                super();
                criteria = new ArrayList<Criterion>();
            }
    
            public boolean isValid() {
                return criteria.size() > 0;
            }
    
            public List<Criterion> getAllCriteria() {
                return criteria;
            }
    
            public List<Criterion> getCriteria() {
                return criteria;
            }
    
            protected void addCriterion(String condition) {
                if (condition == null) {
                    throw new RuntimeException("Value for condition cannot be null");
                }
                criteria.add(new Criterion(condition));
            }
    
            protected void addCriterion(String condition, Object value, String property) {
                if (value == null) {
                    throw new RuntimeException("Value for " + property + " cannot be null");
                }
                criteria.add(new Criterion(condition, value));
            }
    
            protected void addCriterion(String condition, Object value1, Object value2, String property) {
                if (value1 == null || value2 == null) {
                    throw new RuntimeException("Between values for " + property + " cannot be null");
                }
                criteria.add(new Criterion(condition, value1, value2));
            }
    
            public Criteria andIdIsNull() {
                addCriterion("id is null");
                return (Criteria) this;
            }
    
            public Criteria andIdIsNotNull() {
                addCriterion("id is not null");
                return (Criteria) this;
            }
    
            public Criteria andIdEqualTo(Integer value) {
                addCriterion("id =", value, "id");
                return (Criteria) this;
            }
    
            public Criteria andIdNotEqualTo(Integer value) {
                addCriterion("id <>", value, "id");
                return (Criteria) this;
            }
    
            public Criteria andIdGreaterThan(Integer value) {
                addCriterion("id >", value, "id");
                return (Criteria) this;
            }
    
            public Criteria andIdGreaterThanOrEqualTo(Integer value) {
                addCriterion("id >=", value, "id");
                return (Criteria) this;
            }
    
            public Criteria andIdLessThan(Integer value) {
                addCriterion("id <", value, "id");
                return (Criteria) this;
            }
    
            public Criteria andIdLessThanOrEqualTo(Integer value) {
                addCriterion("id <=", value, "id");
                return (Criteria) this;
            }
    
            public Criteria andIdIn(List<Integer> values) {
                addCriterion("id in", values, "id");
                return (Criteria) this;
            }
    
            public Criteria andIdNotIn(List<Integer> values) {
                addCriterion("id not in", values, "id");
                return (Criteria) this;
            }
    
            public Criteria andIdBetween(Integer value1, Integer value2) {
                addCriterion("id between", value1, value2, "id");
                return (Criteria) this;
            }
    
            public Criteria andIdNotBetween(Integer value1, Integer value2) {
                addCriterion("id not between", value1, value2, "id");
                return (Criteria) this;
            }
    
            public Criteria andSexIsNull() {
                addCriterion("sex is null");
                return (Criteria) this;
            }
    
            public Criteria andSexIsNotNull() {
                addCriterion("sex is not null");
                return (Criteria) this;
            }
    
            public Criteria andSexEqualTo(String value) {
                addCriterion("sex =", value, "sex");
                return (Criteria) this;
            }
    
            public Criteria andSexNotEqualTo(String value) {
                addCriterion("sex <>", value, "sex");
                return (Criteria) this;
            }
    
            public Criteria andSexGreaterThan(String value) {
                addCriterion("sex >", value, "sex");
                return (Criteria) this;
            }
    
            public Criteria andSexGreaterThanOrEqualTo(String value) {
                addCriterion("sex >=", value, "sex");
                return (Criteria) this;
            }
    
            public Criteria andSexLessThan(String value) {
                addCriterion("sex <", value, "sex");
                return (Criteria) this;
            }
    
            public Criteria andSexLessThanOrEqualTo(String value) {
                addCriterion("sex <=", value, "sex");
                return (Criteria) this;
            }
    
            public Criteria andSexLike(String value) {
                addCriterion("sex like", value, "sex");
                return (Criteria) this;
            }
    
            public Criteria andSexNotLike(String value) {
                addCriterion("sex not like", value, "sex");
                return (Criteria) this;
            }
    
            public Criteria andSexIn(List<String> values) {
                addCriterion("sex in", values, "sex");
                return (Criteria) this;
            }
    
            public Criteria andSexNotIn(List<String> values) {
                addCriterion("sex not in", values, "sex");
                return (Criteria) this;
            }
    
            public Criteria andSexBetween(String value1, String value2) {
                addCriterion("sex between", value1, value2, "sex");
                return (Criteria) this;
            }
    
            public Criteria andSexNotBetween(String value1, String value2) {
                addCriterion("sex not between", value1, value2, "sex");
                return (Criteria) this;
            }
    
            public Criteria andNameIsNull() {
                addCriterion("name is null");
                return (Criteria) this;
            }
    
            public Criteria andNameIsNotNull() {
                addCriterion("name is not null");
                return (Criteria) this;
            }
    
            public Criteria andNameEqualTo(String value) {
                addCriterion("name =", value, "name");
                return (Criteria) this;
            }
    
            public Criteria andNameNotEqualTo(String value) {
                addCriterion("name <>", value, "name");
                return (Criteria) this;
            }
    
            public Criteria andNameGreaterThan(String value) {
                addCriterion("name >", value, "name");
                return (Criteria) this;
            }
    
            public Criteria andNameGreaterThanOrEqualTo(String value) {
                addCriterion("name >=", value, "name");
                return (Criteria) this;
            }
    
            public Criteria andNameLessThan(String value) {
                addCriterion("name <", value, "name");
                return (Criteria) this;
            }
    
            public Criteria andNameLessThanOrEqualTo(String value) {
                addCriterion("name <=", value, "name");
                return (Criteria) this;
            }
    
            public Criteria andNameLike(String value) {
                addCriterion("name like", value, "name");
                return (Criteria) this;
            }
    
            public Criteria andNameNotLike(String value) {
                addCriterion("name not like", value, "name");
                return (Criteria) this;
            }
    
            public Criteria andNameIn(List<String> values) {
                addCriterion("name in", values, "name");
                return (Criteria) this;
            }
    
            public Criteria andNameNotIn(List<String> values) {
                addCriterion("name not in", values, "name");
                return (Criteria) this;
            }
    
            public Criteria andNameBetween(String value1, String value2) {
                addCriterion("name between", value1, value2, "name");
                return (Criteria) this;
            }
    
            public Criteria andNameNotBetween(String value1, String value2) {
                addCriterion("name not between", value1, value2, "name");
                return (Criteria) this;
            }
        }
    
        public static class Criteria extends GeneratedCriteria {
    
            protected Criteria() {
                super();
            }
        }
    
        public static class Criterion {
            private String condition;
    
            private Object value;
    
            private Object secondValue;
    
            private boolean noValue;
    
            private boolean singleValue;
    
            private boolean betweenValue;
    
            private boolean listValue;
    
            private String typeHandler;
    
            public String getCondition() {
                return condition;
            }
    
            public Object getValue() {
                return value;
            }
    
            public Object getSecondValue() {
                return secondValue;
            }
    
            public boolean isNoValue() {
                return noValue;
            }
    
            public boolean isSingleValue() {
                return singleValue;
            }
    
            public boolean isBetweenValue() {
                return betweenValue;
            }
    
            public boolean isListValue() {
                return listValue;
            }
    
            public String getTypeHandler() {
                return typeHandler;
            }
    
            protected Criterion(String condition) {
                super();
                this.condition = condition;
                this.typeHandler = null;
                this.noValue = true;
            }
    
            protected Criterion(String condition, Object value, String typeHandler) {
                super();
                this.condition = condition;
                this.value = value;
                this.typeHandler = typeHandler;
                if (value instanceof List<?>) {
                    this.listValue = true;
                } else {
                    this.singleValue = true;
                }
            }
    
            protected Criterion(String condition, Object value) {
                this(condition, value, null);
            }
    
            protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
                super();
                this.condition = condition;
                this.value = value;
                this.secondValue = secondValue;
                this.typeHandler = typeHandler;
                this.betweenValue = true;
            }
    
            protected Criterion(String condition, Object value, Object secondValue) {
                this(condition, value, secondValue, null);
            }
        }
    }
    
    UserMapper.java
    package com.ssm.dao;
    import com.ssm.pojo.User;
    import com.ssm.pojo.UserExample;
    import java.util.List;
    import org.apache.ibatis.annotations.Param;
    public interface UserMapper {
        int countByExample(UserExample example);
    
        int deleteByExample(UserExample example);
    
        int deleteByPrimaryKey(Integer id);
    
        int insert(User record);
    
        int insertSelective(User record);
    
        List<User> selectByExample(UserExample example);
    
        User selectByPrimaryKey(Integer id);
    
        int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
    
        int updateByExample(@Param("record") User record, @Param("example") UserExample example);
    
        int updateByPrimaryKeySelective(User record);
    
        int updateByPrimaryKey(User record);
    }
    

    UserMapper.xml (注意标红的地方,主键已经在数据库中设置为自动递增,所以插入sql得手动配一下)

    <?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.ssm.dao.UserMapper" >
      <resultMap id="BaseResultMap" type="com.ssm.pojo.User" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="sex" property="sex" jdbcType="VARCHAR" />
        <result column="name" property="name" jdbcType="VARCHAR" />
      </resultMap>
      <sql id="Example_Where_Clause" >
        <where >
          <foreach collection="oredCriteria" item="criteria" separator="or" >
            <if test="criteria.valid" >
              <trim prefix="(" suffix=")" prefixOverrides="and" >
                <foreach collection="criteria.criteria" item="criterion" >
                  <choose >
                    <when test="criterion.noValue" >
                      and ${criterion.condition}
                    </when>
                    <when test="criterion.singleValue" >
                      and ${criterion.condition} #{criterion.value}
                    </when>
                    <when test="criterion.betweenValue" >
                      and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                    </when>
                    <when test="criterion.listValue" >
                      and ${criterion.condition}
                      <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                        #{listItem}
                      </foreach>
                    </when>
                  </choose>
                </foreach>
              </trim>
            </if>
          </foreach>
        </where>
      </sql>
      <sql id="Update_By_Example_Where_Clause" >
        <where >
          <foreach collection="example.oredCriteria" item="criteria" separator="or" >
            <if test="criteria.valid" >
              <trim prefix="(" suffix=")" prefixOverrides="and" >
                <foreach collection="criteria.criteria" item="criterion" >
                  <choose >
                    <when test="criterion.noValue" >
                      and ${criterion.condition}
                    </when>
                    <when test="criterion.singleValue" >
                      and ${criterion.condition} #{criterion.value}
                    </when>
                    <when test="criterion.betweenValue" >
                      and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                    </when>
                    <when test="criterion.listValue" >
                      and ${criterion.condition}
                      <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                        #{listItem}
                      </foreach>
                    </when>
                  </choose>
                </foreach>
              </trim>
            </if>
          </foreach>
        </where>
      </sql>
      <sql id="Base_Column_List" >
        id, sex, name
      </sql>
      <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.ssm.pojo.UserExample" >
        select
        <if test="distinct" >
          distinct
        </if>
        <include refid="Base_Column_List" />
        from user
        <if test="_parameter != null" >
          <include refid="Example_Where_Clause" />
        </if>
        <if test="orderByClause != null" >
          order by ${orderByClause}
        </if>
      </select>
      <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select 
        <include refid="Base_Column_List" />
        from user
        where id = #{id,jdbcType=INTEGER}
      </select>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from user
        where id = #{id,jdbcType=INTEGER}
      </delete>
      <delete id="deleteByExample" parameterType="com.ssm.pojo.UserExample" >
        delete from user
        <if test="_parameter != null" >
          <include refid="Example_Where_Clause" />
        </if>
      </delete>
      <insert id="insert" parameterType="com.ssm.pojo.User" useGeneratedKeys="true" keyProperty="id">
        insert into user (sex, name
          )
        values (#{sex,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}
          )
      </insert>
      <insert id="insertSelective" parameterType="com.ssm.pojo.User" >
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            id,
          </if>
          <if test="sex != null" >
            sex,
          </if>
          <if test="name != null" >
            name,
          </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            #{id,jdbcType=INTEGER},
          </if>
          <if test="sex != null" >
            #{sex,jdbcType=VARCHAR},
          </if>
          <if test="name != null" >
            #{name,jdbcType=VARCHAR},
          </if>
        </trim>
      </insert>
      <select id="countByExample" parameterType="com.ssm.pojo.UserExample" resultType="java.lang.Integer" >
        select count(*) from user
        <if test="_parameter != null" >
          <include refid="Example_Where_Clause" />
        </if>
      </select>
      <update id="updateByExampleSelective" parameterType="map" >
        update user
        <set >
          <if test="record.id != null" >
            id = #{record.id,jdbcType=INTEGER},
          </if>
          <if test="record.sex != null" >
            sex = #{record.sex,jdbcType=VARCHAR},
          </if>
          <if test="record.name != null" >
            name = #{record.name,jdbcType=VARCHAR},
          </if>
        </set>
        <if test="_parameter != null" >
          <include refid="Update_By_Example_Where_Clause" />
        </if>
      </update>
      <update id="updateByExample" parameterType="map" >
        update user
        set id = #{record.id,jdbcType=INTEGER},
          sex = #{record.sex,jdbcType=VARCHAR},
          name = #{record.name,jdbcType=VARCHAR}
        <if test="_parameter != null" >
          <include refid="Update_By_Example_Where_Clause" />
        </if>
      </update>
      <update id="updateByPrimaryKeySelective" parameterType="com.ssm.pojo.User" >
        update user
        <set >
          <if test="sex != null" >
            sex = #{sex,jdbcType=VARCHAR},
          </if>
          <if test="name != null" >
            name = #{name,jdbcType=VARCHAR},
          </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
      </update>
      <update id="updateByPrimaryKey" parameterType="com.ssm.pojo.User" >
        update user
        set sex = #{sex,jdbcType=VARCHAR},
          name = #{name,jdbcType=VARCHAR}
        where id = #{id,jdbcType=INTEGER}
      </update>
    </mapper>
    

      

    新建一个vo类,UserVo.java

    package com.ssm.vo;
    
    public class UserVo {
    	private String id;
    
          private String sex;
    
          private String name;
    
    	public String getId() {
    		return id;
    	}
    
    	public void setId(String id) {
    		this.id = id;
    	}
    
    	public String getSex() {
    		return sex;
    	}
    
    	public void setSex(String sex) {
    		this.sex = sex;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
        
        
    }
    

      

    新建一个service接口,IUserService.java

    package com.ssm.service;
    import java.util.Map;
    import com.ssm.vo.UserVo;
    public interface IUserService { public Map<String,String> onSave(UserVo userVo); }

    实现IUserService接口,UserServiceImpl.java

    package com.ssm.service.impl;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.ssm.dao.UserMapper;
    import com.ssm.pojo.User;
    import com.ssm.service.IUserService;
    import com.ssm.vo.UserVo;
    
    @Service
    public class UserServiceImpl implements IUserService{
    	
    	@Autowired
    	private UserMapper userMapper;
    	
    	@Override
    	public Map<String, String> onSave(UserVo userVo) {
    		Map<String, String> map = new HashMap<String,String>();
    		try {
    			User user = new User();
    			user.setName(userVo.getName());
    			user.setSex(userVo.getSex());
    			int i = userMapper.insert(user);
    			if(i > 0){
    				map.put("status", "Y");
    				map.put("message", "新增成功");
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return map;
    	}
    	
    }
    
    

     

    新建一个control类,UserController.java

    package com.ssm.controller;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import com.ssm.service.IUserService;
    import com.ssm.vo.UserVo;
    
    @RequestMapping("/user")
    @Controller
    public class UserController {
    	@Autowired
    	private IUserService userService;
    	
    	@RequestMapping("/onSave")
    	@ResponseBody
    	public Map<String,String> onSave(UserVo userVo){
    		Map<String,String> map = new HashMap<String,String>();
    		try {
    			map = userService.onSave(userVo);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return map;
    	}
    }
    

     在WebContent目录下,新增static目录,如下图所示:

    新增index.jsp页面

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    	pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <base href="${pageContext.request.contextPath}/static/"></base>
    <meta charset="utf-8" />
    <script src="js/jquery-1.12.4.min.js"></script>
    
    <script type="text/javascript">
    	$(document).ready(function() {
    		onSave();
    	});
    
    	function onSave() {
    		$.ajax({
    			type : "post",
    			url : "${pageContext.request.contextPath}/user/onSave",
    			async : false,
    			timeout : 30000,
    			data : {
    				"sex":"男",
    				"name":"张三"
    			},
    			dataType : 'json',
    			beforeSend : function(XMLHttpRequest) {
    				
    			},
    			success : function(result) {
    				alert(result.message)
    			},
    			error : function() {
    			}
    		});
    	}
    	
    	
    	
    </script>
    </head>
    
    <body>
    	欢迎您!!!!!!!!!!!!!!!!
    </body>
    
    </html>

    在浏览器地址栏,输入http://127.0.0.1:8080/SSM/index.jsp,回车,结果如下图所示

    看下数据库表

  • 相关阅读:
    矩阵十题(7)
    线段树成段更新 poj 3468 A Simple Problem with Integers
    线段树单点更新 hdu 2795 Billboard
    线段树成段更新 poj 2528 Mayor's posters
    矩阵十题(10)
    矩阵十题(8)
    矩阵十题(5)
    矩阵十题(6)
    矩阵十题(9)
    矩阵十题(4)
  • 原文地址:https://www.cnblogs.com/hjw-zq/p/8854993.html
Copyright © 2011-2022 走看看