單元測試:junitjavascript
日誌:logging,logback,css
JSON:jackson-databindhtml
Spring:spring-core,spring-context,spring-test,spring-tx,spring-beans,spring-jdbc,spring-web,spring-webmvc前端
Mybatis:mybatis,mybatis-spring,pagehelper(分頁插件)java
Mysql:mysql-connector-javamysql
數據源:druidjquery
JSTL:jstlgit
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>TestSsmProject</groupId> <artifactId>TestSsmProject</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>TestSsmProject Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <!-- 實現slf4j接口並整合 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.2</version> </dependency> <!-- JSON --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.7</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.2.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.10.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.12.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.12.RELEASE</version> <scope>test</scope> </dependency> <!-- mybatis分頁插件依賴 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.0.0</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-jxpath/commons-jxpath --> <dependency> <groupId>commons-jxpath</groupId> <artifactId>commons-jxpath</artifactId> <version>1.3</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.ibatis/ibatis-sqlmap --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>24.0-jre</version> </dependency> <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency> </dependencies> <build> <finalName>TestOneMaven</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build> </project>
4.配置文件:github
日誌:web
# Global logging configuration #在開發環境下日誌級別要設置成DEBUG,生產環境設置成info或error log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] --> %m%n
數據庫信息:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/test_crud?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull jdbc.username=root jdbc.password=root validationQuery=SELECT 1
spring配置文件:
<?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:tx="http://www.springframework.org/schema/tx" 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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--掃描配置文件--> <context:property-placeholder location="classpath:db.properties"></context:property-placeholder> <!--掃描--> <context:component-scan base-package="xin.mikey.www"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!--配置數據源--> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.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="${validationQuery}" /> <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> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 配置數據庫表對應的java實體類 --> <property name="typeAliasesPackage" value="xin.mikey.www.pojo" /> <!-- 自動掃描entity目錄, 省掉Configuration.xml裏的手工配置 --> <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property> <property name="mapperLocations" value="classpath:xin/mikey/www/mapper/*.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="xin.mikey.www.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入數據庫鏈接池 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置基於註解的聲明式事務 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
<?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:tx="http://www.springframework.org/schema/tx" 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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--掃描配置文件--> <context:property-placeholder location="classpath:db.properties"></context:property-placeholder> <!--掃描--> <context:component-scan base-package="xin.mikey.www"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!--配置數據源--> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.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="${validationQuery}" /> <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> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 配置數據庫表對應的java實體類 --> <property name="typeAliasesPackage" value="xin.mikey.www.pojo" /> <!-- 自動掃描entity目錄, 省掉Configuration.xml裏的手工配置 --> <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property> <property name="mapperLocations" value="classpath:xin/mikey/www/mapper/*.xml" /> </bean> <!--動態代理自動生成mapper的實現類--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="xin.mikey.www.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入數據庫鏈接池 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置基於註解的聲明式事務 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
SprintMvc配置文件:
<?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" 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.0.xsd"> <!-- 配置自動掃描的包 --> <context:component-scan base-package="xin.mikey.www.controller"></context:component-scan> <!-- 配置視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- default-servlet-handler 將在 SpringMVC 上下文中定義一個 DefaultServletHttpRequestHandler, 它會對進入 DispatcherServlet 的請求進行篩查, 若是發現是沒有通過映射的請求, 就將該請求交由 WEB 應用服務器默認的 Servlet 處理. 若是不是靜態資源的請求,才由 DispatcherServlet 繼續處理 通常 WEB 應用服務器默認的 Servlet 的名稱都是 default. 若所使用的 WEB 服務器的默認 Servlet 名稱不是 default,則須要經過 default-servlet-name 屬性顯式指定 --> <mvc:default-servlet-handler/> <mvc:annotation-driven/> <!--<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">--> <!--<property name="converters">--> <!--<set>--> <!--<ref bean="employeeConverter"/>--> <!--</set>--> <!--</property>--> <!--</bean>--> <!--<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">--> <!--<property name="basename" value="i18n"></property>--> <!--</bean>--> <!--<mvc:view-controller path="/i18n" view-name="i18n"></mvc:view-controller>--> <!--<mvc:view-controller path="/i18n2" view-name="i18n2"></mvc:view-controller>--> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" ></bean> <mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean> <!--<bean class="com.mikey.www.interceptors.FirstInterceptor"></bean>--> <!--配置攔截器(不)做用的路徑--> <!--<mvc:interceptor>--> <!--<mvc:mapping path="/emps"/>--> <!--<bean class="com.mikey.www.interceptors.SecondInterceptor"></bean>--> <!--</mvc:interceptor>--> </mvc:interceptors> <!--配置MultipartResolver--> <!--<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">--> <!--<property name="defaultEncoding" value="UTF-8"></property>--> <!--<property name="maxUploadSize" value="1024000"></property>--> <!--</bean>--> <!--配置自定義攔截器--> <!--<bean class="com.mikey.www.interceptors.FirstInterceptor"></bean>--> <!--<!–配置使用simplemappingException–>--> <!--<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">--> <!--<!–<property name="exceptionAttribute" value="ex"></property>–>--> <!--<property name="exceptionMappings">--> <!--<props>--> <!--<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>--> <!--</props>--> <!--</property>--> <!--</bean>--> </beans>
Mybatis全局配置文件:
<settings> <!-- 打印查詢語句 --> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings>
<?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> <typeAliases> <package name="mikey.www.pojo"></package> </typeAliases> <plugins> <plugin interceptor="com.github.pagehelper.PageHelper"> <!-- 設置數據庫類型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種數據庫--> <property name="dialect" value="mysql"/> </plugin> </plugins> </configuration>
配置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_2_5.xsd" id="WebApp_ID" version="2.5"> <!-- 配置 SpringMVC 的 DispatcherServlet --> <!-- The front controller of this Spring Web application, responsible for handling all application requests --> <!--過濾器解決工程編碼--> <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> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext</param-value> </context-param> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置 HiddenHttpMethodFilter: 把 POST 請求轉爲 DELETE、PUT 請求 --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <!--放行靜態資源文件--> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/js/*</url-pattern> <url-pattern>/css/*</url-pattern> <url-pattern>/fonts/*</url-pattern> <url-pattern>/images/*</url-pattern> </servlet-mapping> </web-app>
項目結構目錄:
編寫mapper接口及映射文件:
<?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="xin.mikey.www.mapper.UserMapper"> <!--<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>--> <resultMap id="userMap" type="xin.mikey.www.pojo.User"> <id column="id" property="id"/> <result column="user_id" property="userid"/> <result column="user_sex" property="sex"/> <result column="user_age" property="age"/> <result column="user_email" property="email"/> <result column="user_name" property="username"/> <result column="user_pwd" property="password"/> </resultMap> <select id="findUserById" parameterType="String" resultMap="userMap"> SELECT * FROM user WHERE id=#{value} </select> <insert id="saveUser" parameterType="user" > insert user(id,user_id,user_sex,user_age,user_email,user_name,user_pwd) value(#{id},#{userid},#{sex},#{age},#{email},#{username},#{password}) </insert> <select id="getAllUser" resultMap="userMap"> SELECT * from USER </select> <select id="findUserByIds" parameterType="int" resultMap="userMap"> SELECT * FROM user where <!--SELECT * FROM `user` WHERE user_id=1 or user_id=2;--> <foreach collection="array" item="id" separator="or"> user_id=#{id} </foreach> </select> <!--update--> <update id="updateUser" parameterType="user"> update user set id=#{id},user_id=#{userid},user_sex=#{sex},user_age=#{age},user_email=#{email},user_name=#{username},user_pwd=#{password} where id=#{id} </update> <!--delete--> <delete id="deleteUser" parameterType="java.lang.String"> delete from user where id=#{value} </delete> <!--userLogin--> <select id="userLogin" parameterType="user" resultMap="userMap"> SELECT * from user where user_email=#{usereamil} and user_pwd=#{password} </select> <!--rigister--> <insert id="userRegister" parameterType="user"> insert USER(id,user_email,user_pwd) value (#{id},#{email},#{password}) </insert> </mapper>
package xin.mikey.www.mapper; import org.springframework.stereotype.Repository; import xin.mikey.www.pojo.User; import java.util.List; /** * @author Mikey * @Title: * @Description: * @date 2018/10/15 18:34 * @Version 1.0 */ @Repository public interface UserMapper { public User findUserById(String id) throws Exception; public List<User> findUserByIds(int[] ids) throws Exception; public void saveUser(User user) throws Exception; public void deleteUser(String id) throws Exception; public void updateUser(User user) throws Exception; public List<User> getAllUser() throws Exception; }
pojo類:
package xin.mikey.www.pojo; import org.springframework.stereotype.Component; /** * @author Mikey * @Title: * @Description: * @date 2018/10/15 18:32 * @Version 1.0 */ @Component public class User { private String id; private Integer userid; private String username; private Integer sex; private Integer age; private String email; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "id='" + id + '\'' + ", userid='" + userid + '\'' + ", username='" + username + '\'' + ", sex=" + sex + ", age=" + age + ", email='" + email + '\'' + ", password='" + password + '\'' + '}'; } }
DAO層:
package xin.mikey.www.dao.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import xin.mikey.www.dao.UserDao; import xin.mikey.www.mapper.UserMapper; import xin.mikey.www.pojo.User; import java.util.List; /** * @author Mikey * @Title: * @Description: * @date 2018/10/15 19:14 * @Version 1.0 */ @Repository public class UserDaoImpl implements UserDao { @Autowired private UserMapper userMapper; @Override public User findUserById(String id) throws Exception { return userMapper.findUserById(id); } @Override public List<User> findUserByIds(int[] ids) throws Exception { return userMapper.findUserByIds(ids); } @Override public void saveUser(User user) throws Exception { userMapper.saveUser(user); } @Override public void deleteUser(String id) throws Exception { userMapper.deleteUser(id); } @Override public void updateUser(User user) throws Exception { userMapper.updateUser(user); } @Override public List<User> getAllUser() throws Exception { List<User> allUser =userMapper.getAllUser(); return allUser; } }
package xin.mikey.www.dao; import org.springframework.stereotype.Repository; import xin.mikey.www.pojo.User; import java.util.List; /** * @author Mikey * @Title: * @Description: * @date 2018/10/15 19:13 * @Version 1.0 */ @Repository public interface UserDao{ public User findUserById(String id) throws Exception; public List<User> findUserByIds(int[] ids) throws Exception; public void saveUser(User user) throws Exception; public void deleteUser(String id) throws Exception; public void updateUser(User user) throws Exception; public List<User> getAllUser() throws Exception; }
Service層:
package xin.mikey.www.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import xin.mikey.www.dao.UserDao; import xin.mikey.www.pojo.User; import xin.mikey.www.service.UserService; import java.util.List; /** * @author Mikey * @Title: * @Description: * @date 2018/10/15 19:30 * @Version 1.0 */ @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public User findUserById(String id) throws Exception { return userDao.findUserById(id); } @Override public List<User> findUserByIds(int[] ids) throws Exception { return this.userDao.findUserByIds(ids); } @Override public void saveUser(User user) throws Exception { this.userDao.saveUser(user); } @Override public void deleteUser(String id) throws Exception { this.userDao.deleteUser(id); } @Override public void updateUser(User user) throws Exception { this.userDao.updateUser(user); } @Override public List<User> getAllUser() throws Exception { return this.userDao.getAllUser(); } }
package xin.mikey.www.service; import org.springframework.stereotype.Service; import xin.mikey.www.pojo.User; import java.util.List; /** * @author Mikey * @Title: * @Description: * @date 2018/10/15 19:29 * @Version 1.0 */ @Service public interface UserService { public User findUserById(String id) throws Exception; public List<User> findUserByIds(int[] ids) throws Exception; public void saveUser(User user) throws Exception; public void deleteUser(String id) throws Exception; public void updateUser(User user) throws Exception; public List<User> getAllUser() throws Exception; }
Controller層:
package xin.mikey.www.controller; import com.sun.org.glassfish.gmbal.ParameterNames; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestParam; import xin.mikey.www.pojo.User; import java.util.List; import java.util.Map; /** * @author Mikey * @Title: * @Description: * @date 2018/10/15 19:13 * @Version 1.0 */ @Controller public interface UserController { /** * 經過id查找用戶信息 * @return * @throws Exception */ public String findUserById(@RequestParam("userid") String id,Map<String,Object> map) throws Exception; public String findUserByIds(@RequestParam("ids") String ids,Map<String,Object> map) throws Exception; public String saveUser(User user,Map<String,Object> map) throws Exception; public String deleteUser(String id,Map<String,Object> map) throws Exception; public String updateUser(User user,Map<String,Object> map) throws Exception; public String userLogin(@RequestParam("eamil") String email,@RequestParam("password") String pwd,Map<String,Object> map); }
package xin.mikey.www.controller.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.google.common.collect.Maps; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import xin.mikey.www.controller.UserController; import xin.mikey.www.pojo.User; import xin.mikey.www.service.UserService; import java.util.List; import java.util.Map; import java.util.UUID; /** * @author Mikey * @Title: * @Description: * @date 2018/10/15 19:32 * @Version 1.0 */ @Controller @SessionAttributes("user") @RequestMapping("/user") public class UserControllerImpl implements UserController { private String SCU="success"; @Qualifier("userServiceImpl") @Autowired private UserService userService; @RequestMapping("/loginUI") public String loginUI(){ System.out.println("loginUI"); return "login"; } @RequestMapping("/findUserById/{id}") public String findUserById(@PathVariable("id") String id, Map<String,Object> map) throws Exception { User user= this.userService.findUserById(id); map.put("user",user); return "edit"; } @Override @RequestMapping("/findUserByIds") public String findUserByIds(String ids, Map<String,Object> map) throws Exception { // this.userService.findUserByIds(); return null; } @RequestMapping("/addWork") public String addWorkUI(){ return "addwork"; } @Override @RequestMapping("/saveUser") public String saveUser(User user, Map<String,Object> map) throws Exception { user.setId(UUID.randomUUID().toString()); user.setPassword("000"); userService.saveUser(user); return "redirect:addWork"; } @Override @RequestMapping("/deleteUser/{id}") public String deleteUser(@PathVariable("id") String id, Map<String,Object> map) throws Exception { System.out.println("ID="+id); userService.deleteUser(id); return "redirect:/user/getAll"; } @Override @RequestMapping(value = "/updateUser",method = RequestMethod.PUT) public String updateUser(User user, Map<String,Object> map) throws Exception { userService.updateUser(user); return "redirect:/user/getAll"; } @Override @RequestMapping("/login") public String userLogin(String email, String pwd, Map<String, Object> map) { System.out.println("Message="+email+"//"+pwd); return "main"; } @RequestMapping("/getAll") public String getAllUser(Map<String,Object> map){ List<User> list= null; try { list = userService.getAllUser(); } catch (Exception e) { e.printStackTrace(); } map.put("users",list); return "showAll"; } @RequestMapping("/getAllPage/{str_pageNo}") public ModelAndView getAllUserPage(@PathVariable(value = "str_pageNo",required = false) String str_pageNo, Map<String,Object> maps) throws Exception { //拿到用戶須要的是哪一頁的文章數據 if(str_pageNo == null){ //開始使用分頁插件,準備查詢第一頁的8條數據 PageHelper.startPage(1, 8); } else{ //準備查詢 第X頁 的8條數據 PageHelper.startPage(Integer.parseInt(str_pageNo), 8); } //參數Map final Map<String,Object> map = Maps.newHashMap(); //獲取全部做者的全部文章 final List<User> articles = userService.getAllUser(); //將查詢結果放入分頁控件中 final PageInfo<User> pageInfo=new PageInfo<User>(articles); //組裝數據,在JSP頁面能夠經過 ${articles} 或者 ${pageInfo}請求獲取數據 map.put("users",articles); map.put("pageInfo",pageInfo); //返回某個具體的JSP頁面,而且攜帶上map裏面的存儲的數據 return new ModelAndView("showAll",map); } }
報錯:
發現target沒有映射文件:
解決方法:
pom文件加入:
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources>
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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.atguigu</groupId> <artifactId>ssm-crud</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <!--引入項目依賴的jar包 --> <!-- SpringMVC、Spring --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependencies> <!--引入pageHelper分頁插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.0.0</version> </dependency> <!-- MBG --> <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- 返回json字符串的支持 --> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8</version> </dependency> <!--JSR303數據校驗支持;tomcat7及以上的服務器, tomcat7如下的服務器:el表達式。額外給服務器的lib包中替換新的標準的el --> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency> <!-- Spring-Jdbc --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!--Spring-test --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- Spring面向切面編程 --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!--MyBatis --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <!-- MyBatis整合Spring的適配包 --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- 數據庫鏈接池、驅動 --> <!-- https://mvnrepository.com/artifact/c3p0/c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> </dependency> <!-- (jstl,servlet-api,junit) --> <!-- https://mvnrepository.com/artifact/jstl/jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <!-- junit --> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> </project>
spring配置文件:
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan base-package="com.atguigu"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- Spring的配置文件,這裏主要配置和業務邏輯有關的 --> <!--=================== 數據源,事務控制,xxx ================--> <context:property-placeholder location="classpath:dbconfig.properties" /> <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--================== 配置和MyBatis的整合=============== --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定mybatis全局配置文件的位置 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="dataSource" ref="pooledDataSource"></property> <!-- 指定mybatis,mapper文件的位置 --> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean> <!-- 配置掃描器,將mybatis接口的實現加入到ioc容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--掃描全部dao接口的實現,加入到ioc容器中 --> <property name="basePackage" value="com.atguigu.crud.dao"></property> </bean> <!-- 配置一個能夠執行批量的sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> <constructor-arg name="executorType" value="BATCH"></constructor-arg> </bean> <!--============================================= --> <!-- ===============事務控制的配置 ================--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--控制住數據源 --> <property name="dataSource" ref="pooledDataSource"></property> </bean> <!--開啓基於註解的事務,使用xml配置形式的事務(必要主要的都是使用配置式) --> <aop:config> <!-- 切入點表達式 --> <aop:pointcut expression="execution(* com.atguigu.crud.service..*(..))" id="txPoint"/> <!-- 配置事務加強 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/> </aop:config> <!--配置事務加強,事務如何切入 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 全部方法都是事務方法 --> <tx:method name="*"/> <!--以get開始的全部方法 --> <tx:method name="get*" read-only="true"/> </tx:attributes> </tx:advice> <!-- Spring配置文件的核心點(數據源、與mybatis的整合,事務控制) --> </beans>
springMvc配置文件;
<?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" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!--SpringMVC的配置文件,包含網站跳轉邏輯的控制,配置 --> <context:component-scan base-package="com.atguigu" use-default-filters="false"> <!--只掃描控制器。 --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--配置視圖解析器,方便頁面返回 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--兩個標準配置 --> <!-- 將springmvc不能處理的請求交給tomcat --> <mvc:default-servlet-handler/> <!-- 能支持springmvc更高級的一些功能,JSR303校驗,快捷的ajax...映射動態請求 --> <mvc:annotation-driven/> </beans>
myBatis配置文件:
<?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="mapUnderscoreToCamelCase" value="true"/> </settings> <typeAliases> <package name="com.atguigu.crud.bean"/> </typeAliases> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!--分頁參數合理化 --> <property name="reasonable" value="true"/> </plugin> </plugins> </configuration>
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_2_5.xsd" id="WebApp_ID" version="2.5"> <!--一、啓動Spring的容器 --> <!-- needed for ContextLoaderListener --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- Bootstraps the root web application context before servlet initialization --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--二、springmvc的前端控制器,攔截全部請求 --> <!-- The front controller of this Spring Web application, responsible for handling all application requests --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>dispatcherServlet</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>forceRequestEncoding</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 四、使用Rest風格的URI,將頁面普通的post請求轉爲指定的delete或者put請求 --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>HttpPutFormContentFilter</filter-name> <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class> </filter> <filter-mapping> <filter-name>HttpPutFormContentFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
數據庫參數配置:
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456
日誌配置文件:
...................
逆向文件:
<?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="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- 配置數據庫鏈接 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/ssm_crud" userId="root" password="123456"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 指定javaBean生成的位置 --> <javaModelGenerator targetPackage="com.atguigu.crud.bean" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--指定sql映射文件生成的位置 --> <sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 指定dao接口生成的位置,mapper接口 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.atguigu.crud.dao" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- table指定每一個表的生成策略 --> <table tableName="tbl_emp" domainObjectName="Employee"></table> <table tableName="tbl_dept" domainObjectName="Department"></table> </context> </generatorConfiguration>
批量插入數據:
package com.atguigu.crud.test; import java.util.UUID; import org.apache.ibatis.session.SqlSession; 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.atguigu.crud.bean.Employee; import com.atguigu.crud.dao.DepartmentMapper; import com.atguigu.crud.dao.EmployeeMapper; /** * 測試dao層的工做 * @author lfy *推薦Spring的項目就可使用Spring的單元測試,能夠自動注入咱們須要的組件 *一、導入SpringTest模塊 *二、@ContextConfiguration指定Spring配置文件的位置 *三、直接autowired要使用的組件便可 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext.xml"}) public class MapperTest { @Autowired DepartmentMapper departmentMapper; @Autowired EmployeeMapper employeeMapper; @Autowired SqlSession sqlSession; /** * 測試DepartmentMapper */ @Test public void testCRUD(){ /* //一、建立SpringIOC容器 ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); //二、從容器中獲取mapper DepartmentMapper bean = ioc.getBean(DepartmentMapper.class);*/ System.out.println(departmentMapper); //一、插入幾個部門 // departmentMapper.insertSelective(new Department(null, "開發部")); // departmentMapper.insertSelective(new Department(null, "測試部")); //二、生成員工數據,測試員工插入 employeeMapper.insertSelective(new Employee(null, "Jerry", "M", "Jerry@atguigu.com", 1)); //三、批量插入多個員工;批量,使用能夠執行批量操做的sqlSession。 // for(){ // employeeMapper.insertSelective(new Employee(null, , "M", "Jerry@atguigu.com", 1)); // } EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); for(int i = 0;i<1000;i++){ String uid = UUID.randomUUID().toString().substring(0,5)+i; mapper.insertSelective(new Employee(null,uid, "M", uid+"@atguigu.com", 1)); } System.out.println("批量完成"); } }
測試生成mapper文件:
package com.atguigu.crud.test; import java.io.File; import java.util.ArrayList; import java.util.List; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; public class MBGTest { public static void main(String[] args) throws Exception { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("mbg.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); } }
Mapper文件:
package com.atguigu.crud.dao; import com.atguigu.crud.bean.Employee; import com.atguigu.crud.bean.EmployeeExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface EmployeeMapper { long countByExample(EmployeeExample example); int deleteByExample(EmployeeExample example); int deleteByPrimaryKey(Integer empId); int insert(Employee record); int insertSelective(Employee record); List<Employee> selectByExample(EmployeeExample example); Employee selectByPrimaryKey(Integer empId); List<Employee> selectByExampleWithDept(EmployeeExample example); Employee selectByPrimaryKeyWithDept(Integer empId); int updateByExampleSelective(@Param("record") Employee record, @Param("example") EmployeeExample example); int updateByExample(@Param("record") Employee record, @Param("example") EmployeeExample example); int updateByPrimaryKeySelective(Employee record); int updateByPrimaryKey(Employee record); }
<?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.atguigu.crud.dao.EmployeeMapper"> <resultMap id="BaseResultMap" type="com.atguigu.crud.bean.Employee"> <id column="emp_id" jdbcType="INTEGER" property="empId" /> <result column="emp_name" jdbcType="VARCHAR" property="empName" /> <result column="gender" jdbcType="CHAR" property="gender" /> <result column="email" jdbcType="VARCHAR" property="email" /> <result column="d_id" jdbcType="INTEGER" property="dId" /> </resultMap> <resultMap type="com.atguigu.crud.bean.Employee" id="WithDeptResultMap"> <id column="emp_id" jdbcType="INTEGER" property="empId" /> <result column="emp_name" jdbcType="VARCHAR" property="empName" /> <result column="gender" jdbcType="CHAR" property="gender" /> <result column="email" jdbcType="VARCHAR" property="email" /> <result column="d_id" jdbcType="INTEGER" property="dId" /> <!-- 指定聯合查詢出的部門字段的封裝 --> <association property="department" javaType="com.atguigu.crud.bean.Department"> <id column="dept_id" property="deptId"/> <result column="dept_name" property="deptName"/> </association> </resultMap> <sql id="Example_Where_Clause"> <where> <foreach collection="oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <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 close=")" collection="criterion.value" item="listItem" open="(" 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="(" prefixOverrides="and" suffix=")"> <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 close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Base_Column_List"> emp_id, emp_name, gender, email, d_id </sql> <sql id="WithDept_Column_List"> e.emp_id, e.emp_name, e.gender, e.email, e.d_id,d.dept_id,d.dept_name </sql> <!-- List<Employee> selectByExampleWithDept(EmployeeExample example); Employee selectByPrimaryKeyWithDept(Integer empId); --> <!-- 查詢員工同時帶部門信息 --> <select id="selectByExampleWithDept" resultMap="WithDeptResultMap"> select <if test="distinct"> distinct </if> <include refid="WithDept_Column_List" /> FROM tbl_emp e left join tbl_dept d on e.`d_id`=d.`dept_id` <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> </select> <select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap"> select <include refid="WithDept_Column_List" /> FROM tbl_emp e left join tbl_dept d on e.`d_id`=d.`dept_id` where emp_id = #{empId,jdbcType=INTEGER} </select> <!-- 查詢員工不帶部門信息的 --> <select id="selectByExample" parameterType="com.atguigu.crud.bean.EmployeeExample" resultMap="BaseResultMap"> select <if test="distinct"> distinct </if> <include refid="Base_Column_List" /> from tbl_emp <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> </select> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from tbl_emp where emp_id = #{empId,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from tbl_emp where emp_id = #{empId,jdbcType=INTEGER} </delete> <delete id="deleteByExample" parameterType="com.atguigu.crud.bean.EmployeeExample"> delete from tbl_emp <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" parameterType="com.atguigu.crud.bean.Employee"> insert into tbl_emp (emp_id, emp_name, gender, email, d_id) values (#{empId,jdbcType=INTEGER}, #{empName,jdbcType=VARCHAR}, #{gender,jdbcType=CHAR}, #{email,jdbcType=VARCHAR}, #{dId,jdbcType=INTEGER}) </insert> <insert id="insertSelective" parameterType="com.atguigu.crud.bean.Employee"> insert into tbl_emp <trim prefix="(" suffix=")" suffixOverrides=","> <if test="empId != null"> emp_id, </if> <if test="empName != null"> emp_name, </if> <if test="gender != null"> gender, </if> <if test="email != null"> email, </if> <if test="dId != null"> d_id, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="empId != null"> #{empId,jdbcType=INTEGER}, </if> <if test="empName != null"> #{empName,jdbcType=VARCHAR}, </if> <if test="gender != null"> #{gender,jdbcType=CHAR}, </if> <if test="email != null"> #{email,jdbcType=VARCHAR}, </if> <if test="dId != null"> #{dId,jdbcType=INTEGER}, </if> </trim> </insert> <select id="countByExample" parameterType="com.atguigu.crud.bean.EmployeeExample" resultType="java.lang.Long"> select count(*) from tbl_emp <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </select> <update id="updateByExampleSelective" parameterType="map"> update tbl_emp <set> <if test="record.empId != null"> emp_id = #{record.empId,jdbcType=INTEGER}, </if> <if test="record.empName != null"> emp_name = #{record.empName,jdbcType=VARCHAR}, </if> <if test="record.gender != null"> gender = #{record.gender,jdbcType=CHAR}, </if> <if test="record.email != null"> email = #{record.email,jdbcType=VARCHAR}, </if> <if test="record.dId != null"> d_id = #{record.dId,jdbcType=INTEGER}, </if> </set> <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByExample" parameterType="map"> update tbl_emp set emp_id = #{record.empId,jdbcType=INTEGER}, emp_name = #{record.empName,jdbcType=VARCHAR}, gender = #{record.gender,jdbcType=CHAR}, email = #{record.email,jdbcType=VARCHAR}, d_id = #{record.dId,jdbcType=INTEGER} <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByPrimaryKeySelective" parameterType="com.atguigu.crud.bean.Employee"> update tbl_emp <set> <if test="empName != null"> emp_name = #{empName,jdbcType=VARCHAR}, </if> <if test="gender != null"> gender = #{gender,jdbcType=CHAR}, </if> <if test="email != null"> email = #{email,jdbcType=VARCHAR}, </if> <if test="dId != null"> d_id = #{dId,jdbcType=INTEGER}, </if> </set> where emp_id = #{empId,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.atguigu.crud.bean.Employee"> update tbl_emp set emp_name = #{empName,jdbcType=VARCHAR}, gender = #{gender,jdbcType=CHAR}, email = #{email,jdbcType=VARCHAR}, d_id = #{dId,jdbcType=INTEGER} where emp_id = #{empId,jdbcType=INTEGER} </update> </mapper>
package com.atguigu.crud.dao; import com.atguigu.crud.bean.Department; import com.atguigu.crud.bean.DepartmentExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface DepartmentMapper { long countByExample(DepartmentExample example); int deleteByExample(DepartmentExample example); int deleteByPrimaryKey(Integer deptId); int insert(Department record); int insertSelective(Department record); List<Department> selectByExample(DepartmentExample example); Department selectByPrimaryKey(Integer deptId); int updateByExampleSelective(@Param("record") Department record, @Param("example") DepartmentExample example); int updateByExample(@Param("record") Department record, @Param("example") DepartmentExample example); int updateByPrimaryKeySelective(Department record); int updateByPrimaryKey(Department record); }
<?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.atguigu.crud.dao.DepartmentMapper"> <resultMap id="BaseResultMap" type="com.atguigu.crud.bean.Department"> <id column="dept_id" jdbcType="INTEGER" property="deptId" /> <result column="dept_name" jdbcType="VARCHAR" property="deptName" /> </resultMap> <sql id="Example_Where_Clause"> <where> <foreach collection="oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <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 close=")" collection="criterion.value" item="listItem" open="(" 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="(" prefixOverrides="and" suffix=")"> <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 close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Base_Column_List"> dept_id, dept_name </sql> <select id="selectByExample" parameterType="com.atguigu.crud.bean.DepartmentExample" resultMap="BaseResultMap"> select <if test="distinct"> distinct </if> <include refid="Base_Column_List" /> from tbl_dept <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> </select> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from tbl_dept where dept_id = #{deptId,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from tbl_dept where dept_id = #{deptId,jdbcType=INTEGER} </delete> <delete id="deleteByExample" parameterType="com.atguigu.crud.bean.DepartmentExample"> delete from tbl_dept <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" parameterType="com.atguigu.crud.bean.Department"> insert into tbl_dept (dept_id, dept_name) values (#{deptId,jdbcType=INTEGER}, #{deptName,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.atguigu.crud.bean.Department"> insert into tbl_dept <trim prefix="(" suffix=")" suffixOverrides=","> <if test="deptId != null"> dept_id, </if> <if test="deptName != null"> dept_name, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="deptId != null"> #{deptId,jdbcType=INTEGER}, </if> <if test="deptName != null"> #{deptName,jdbcType=VARCHAR}, </if> </trim> </insert> <select id="countByExample" parameterType="com.atguigu.crud.bean.DepartmentExample" resultType="java.lang.Long"> select count(*) from tbl_dept <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </select> <update id="updateByExampleSelective" parameterType="map"> update tbl_dept <set> <if test="record.deptId != null"> dept_id = #{record.deptId,jdbcType=INTEGER}, </if> <if test="record.deptName != null"> dept_name = #{record.deptName,jdbcType=VARCHAR}, </if> </set> <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByExample" parameterType="map"> update tbl_dept set dept_id = #{record.deptId,jdbcType=INTEGER}, dept_name = #{record.deptName,jdbcType=VARCHAR} <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByPrimaryKeySelective" parameterType="com.atguigu.crud.bean.Department"> update tbl_dept <set> <if test="deptName != null"> dept_name = #{deptName,jdbcType=VARCHAR}, </if> </set> where dept_id = #{deptId,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.atguigu.crud.bean.Department"> update tbl_dept set dept_name = #{deptName,jdbcType=VARCHAR} where dept_id = #{deptId,jdbcType=INTEGER} </update> </mapper>
pojo類:
package com.atguigu.crud.bean; import java.util.HashMap; import java.util.Map; /** * 通用的返回的類 * * @author lfy * */ public class Msg { //狀態碼 100-成功 200-失敗 private int code; //提示信息 private String msg; //用戶要返回給瀏覽器的數據 private Map<String, Object> extend = new HashMap<String, Object>(); public static Msg success(){ Msg result = new Msg(); result.setCode(100); result.setMsg("處理成功!"); return result; } public static Msg fail(){ Msg result = new Msg(); result.setCode(200); result.setMsg("處理失敗!"); return result; } public Msg add(String key,Object value){ this.getExtend().put(key, value); return this; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Map<String, Object> getExtend() { return extend; } public void setExtend(Map<String, Object> extend) { this.extend = extend; } }
package com.atguigu.crud.bean; import java.util.ArrayList; import java.util.List; public class EmployeeExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public EmployeeExample() { 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 andEmpIdIsNull() { addCriterion("emp_id is null"); return (Criteria) this; } public Criteria andEmpIdIsNotNull() { addCriterion("emp_id is not null"); return (Criteria) this; } public Criteria andEmpIdEqualTo(Integer value) { addCriterion("emp_id =", value, "empId"); return (Criteria) this; } public Criteria andEmpIdNotEqualTo(Integer value) { addCriterion("emp_id <>", value, "empId"); return (Criteria) this; } public Criteria andEmpIdGreaterThan(Integer value) { addCriterion("emp_id >", value, "empId"); return (Criteria) this; } public Criteria andEmpIdGreaterThanOrEqualTo(Integer value) { addCriterion("emp_id >=", value, "empId"); return (Criteria) this; } public Criteria andEmpIdLessThan(Integer value) { addCriterion("emp_id <", value, "empId"); return (Criteria) this; } public Criteria andEmpIdLessThanOrEqualTo(Integer value) { addCriterion("emp_id <=", value, "empId"); return (Criteria) this; } public Criteria andEmpIdIn(List<Integer> values) { addCriterion("emp_id in", values, "empId"); return (Criteria) this; } public Criteria andEmpIdNotIn(List<Integer> values) { addCriterion("emp_id not in", values, "empId"); return (Criteria) this; } public Criteria andEmpIdBetween(Integer value1, Integer value2) { addCriterion("emp_id between", value1, value2, "empId"); return (Criteria) this; } public Criteria andEmpIdNotBetween(Integer value1, Integer value2) { addCriterion("emp_id not between", value1, value2, "empId"); return (Criteria) this; } public Criteria andEmpNameIsNull() { addCriterion("emp_name is null"); return (Criteria) this; } public Criteria andEmpNameIsNotNull() { addCriterion("emp_name is not null"); return (Criteria) this; } public Criteria andEmpNameEqualTo(String value) { addCriterion("emp_name =", value, "empName"); return (Criteria) this; } public Criteria andEmpNameNotEqualTo(String value) { addCriterion("emp_name <>", value, "empName"); return (Criteria) this; } public Criteria andEmpNameGreaterThan(String value) { addCriterion("emp_name >", value, "empName"); return (Criteria) this; } public Criteria andEmpNameGreaterThanOrEqualTo(String value) { addCriterion("emp_name >=", value, "empName"); return (Criteria) this; } public Criteria andEmpNameLessThan(String value) { addCriterion("emp_name <", value, "empName"); return (Criteria) this; } public Criteria andEmpNameLessThanOrEqualTo(String value) { addCriterion("emp_name <=", value, "empName"); return (Criteria) this; } public Criteria andEmpNameLike(String value) { addCriterion("emp_name like", value, "empName"); return (Criteria) this; } public Criteria andEmpNameNotLike(String value) { addCriterion("emp_name not like", value, "empName"); return (Criteria) this; } public Criteria andEmpNameIn(List<String> values) { addCriterion("emp_name in", values, "empName"); return (Criteria) this; } public Criteria andEmpNameNotIn(List<String> values) { addCriterion("emp_name not in", values, "empName"); return (Criteria) this; } public Criteria andEmpNameBetween(String value1, String value2) { addCriterion("emp_name between", value1, value2, "empName"); return (Criteria) this; } public Criteria andEmpNameNotBetween(String value1, String value2) { addCriterion("emp_name not between", value1, value2, "empName"); return (Criteria) this; } public Criteria andGenderIsNull() { addCriterion("gender is null"); return (Criteria) this; } public Criteria andGenderIsNotNull() { addCriterion("gender is not null"); return (Criteria) this; } public Criteria andGenderEqualTo(String value) { addCriterion("gender =", value, "gender"); return (Criteria) this; } public Criteria andGenderNotEqualTo(String value) { addCriterion("gender <>", value, "gender"); return (Criteria) this; } public Criteria andGenderGreaterThan(String value) { addCriterion("gender >", value, "gender"); return (Criteria) this; } public Criteria andGenderGreaterThanOrEqualTo(String value) { addCriterion("gender >=", value, "gender"); return (Criteria) this; } public Criteria andGenderLessThan(String value) { addCriterion("gender <", value, "gender"); return (Criteria) this; } public Criteria andGenderLessThanOrEqualTo(String value) { addCriterion("gender <=", value, "gender"); return (Criteria) this; } public Criteria andGenderLike(String value) { addCriterion("gender like", value, "gender"); return (Criteria) this; } public Criteria andGenderNotLike(String value) { addCriterion("gender not like", value, "gender"); return (Criteria) this; } public Criteria andGenderIn(List<String> values) { addCriterion("gender in", values, "gender"); return (Criteria) this; } public Criteria andGenderNotIn(List<String> values) { addCriterion("gender not in", values, "gender"); return (Criteria) this; } public Criteria andGenderBetween(String value1, String value2) { addCriterion("gender between", value1, value2, "gender"); return (Criteria) this; } public Criteria andGenderNotBetween(String value1, String value2) { addCriterion("gender not between", value1, value2, "gender"); return (Criteria) this; } public Criteria andEmailIsNull() { addCriterion("email is null"); return (Criteria) this; } public Criteria andEmailIsNotNull() { addCriterion("email is not null"); return (Criteria) this; } public Criteria andEmailEqualTo(String value) { addCriterion("email =", value, "email"); return (Criteria) this; } public Criteria andEmailNotEqualTo(String value) { addCriterion("email <>", value, "email"); return (Criteria) this; } public Criteria andEmailGreaterThan(String value) { addCriterion("email >", value, "email"); return (Criteria) this; } public Criteria andEmailGreaterThanOrEqualTo(String value) { addCriterion("email >=", value, "email"); return (Criteria) this; } public Criteria andEmailLessThan(String value) { addCriterion("email <", value, "email"); return (Criteria) this; } public Criteria andEmailLessThanOrEqualTo(String value) { addCriterion("email <=", value, "email"); return (Criteria) this; } public Criteria andEmailLike(String value) { addCriterion("email like", value, "email"); return (Criteria) this; } public Criteria andEmailNotLike(String value) { addCriterion("email not like", value, "email"); return (Criteria) this; } public Criteria andEmailIn(List<String> values) { addCriterion("email in", values, "email"); return (Criteria) this; } public Criteria andEmailNotIn(List<String> values) { addCriterion("email not in", values, "email"); return (Criteria) this; } public Criteria andEmailBetween(String value1, String value2) { addCriterion("email between", value1, value2, "email"); return (Criteria) this; } public Criteria andEmailNotBetween(String value1, String value2) { addCriterion("email not between", value1, value2, "email"); return (Criteria) this; } public Criteria andDIdIsNull() { addCriterion("d_id is null"); return (Criteria) this; } public Criteria andDIdIsNotNull() { addCriterion("d_id is not null"); return (Criteria) this; } public Criteria andDIdEqualTo(Integer value) { addCriterion("d_id =", value, "dId"); return (Criteria) this; } public Criteria andDIdNotEqualTo(Integer value) { addCriterion("d_id <>", value, "dId"); return (Criteria) this; } public Criteria andDIdGreaterThan(Integer value) { addCriterion("d_id >", value, "dId"); return (Criteria) this; } public Criteria andDIdGreaterThanOrEqualTo(Integer value) { addCriterion("d_id >=", value, "dId"); return (Criteria) this; } public Criteria andDIdLessThan(Integer value) { addCriterion("d_id <", value, "dId"); return (Criteria) this; } public Criteria andDIdLessThanOrEqualTo(Integer value) { addCriterion("d_id <=", value, "dId"); return (Criteria) this; } public Criteria andDIdIn(List<Integer> values) { addCriterion("d_id in", values, "dId"); return (Criteria) this; } public Criteria andDIdNotIn(List<Integer> values) { addCriterion("d_id not in", values, "dId"); return (Criteria) this; } public Criteria andDIdBetween(Integer value1, Integer value2) { addCriterion("d_id between", value1, value2, "dId"); return (Criteria) this; } public Criteria andDIdNotBetween(Integer value1, Integer value2) { addCriterion("d_id not between", value1, value2, "dId"); 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); } } }
package com.atguigu.crud.bean; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.Length; public class Employee { private Integer empId; @Pattern(regexp="(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})" ,message="用戶名必須是2-5位中文或者6-16位英文和數字的組合") private String empName; private String gender; //@Email @Pattern(regexp="^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$", message="郵箱格式不正確") private String email; private Integer dId; //但願查詢員工的同時部門信息也是查詢好的 private Department department; @Override public String toString() { return "Employee [empId=" + empId + ", empName=" + empName + ", gender=" + gender + ", email=" + email + ", dId=" + dId + "]"; } public Employee() { super(); } public Employee(Integer empId, String empName, String gender, String email, Integer dId) { super(); this.empId = empId; this.empName = empName; this.gender = gender; this.email = email; this.dId = dId; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public Integer getEmpId() { return empId; } public void setEmpId(Integer empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName == null ? null : empName.trim(); } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender == null ? null : gender.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public Integer getdId() { return dId; } public void setdId(Integer dId) { this.dId = dId; } }
package com.atguigu.crud.bean; import java.util.ArrayList; import java.util.List; public class DepartmentExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public DepartmentExample() { 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 andDeptIdIsNull() { addCriterion("dept_id is null"); return (Criteria) this; } public Criteria andDeptIdIsNotNull() { addCriterion("dept_id is not null"); return (Criteria) this; } public Criteria andDeptIdEqualTo(Integer value) { addCriterion("dept_id =", value, "deptId"); return (Criteria) this; } public Criteria andDeptIdNotEqualTo(Integer value) { addCriterion("dept_id <>", value, "deptId"); return (Criteria) this; } public Criteria andDeptIdGreaterThan(Integer value) { addCriterion("dept_id >", value, "deptId"); return (Criteria) this; } public Criteria andDeptIdGreaterThanOrEqualTo(Integer value) { addCriterion("dept_id >=", value, "deptId"); return (Criteria) this; } public Criteria andDeptIdLessThan(Integer value) { addCriterion("dept_id <", value, "deptId"); return (Criteria) this; } public Criteria andDeptIdLessThanOrEqualTo(Integer value) { addCriterion("dept_id <=", value, "deptId"); return (Criteria) this; } public Criteria andDeptIdIn(List<Integer> values) { addCriterion("dept_id in", values, "deptId"); return (Criteria) this; } public Criteria andDeptIdNotIn(List<Integer> values) { addCriterion("dept_id not in", values, "deptId"); return (Criteria) this; } public Criteria andDeptIdBetween(Integer value1, Integer value2) { addCriterion("dept_id between", value1, value2, "deptId"); return (Criteria) this; } public Criteria andDeptIdNotBetween(Integer value1, Integer value2) { addCriterion("dept_id not between", value1, value2, "deptId"); return (Criteria) this; } public Criteria andDeptNameIsNull() { addCriterion("dept_name is null"); return (Criteria) this; } public Criteria andDeptNameIsNotNull() { addCriterion("dept_name is not null"); return (Criteria) this; } public Criteria andDeptNameEqualTo(String value) { addCriterion("dept_name =", value, "deptName"); return (Criteria) this; } public Criteria andDeptNameNotEqualTo(String value) { addCriterion("dept_name <>", value, "deptName"); return (Criteria) this; } public Criteria andDeptNameGreaterThan(String value) { addCriterion("dept_name >", value, "deptName"); return (Criteria) this; } public Criteria andDeptNameGreaterThanOrEqualTo(String value) { addCriterion("dept_name >=", value, "deptName"); return (Criteria) this; } public Criteria andDeptNameLessThan(String value) { addCriterion("dept_name <", value, "deptName"); return (Criteria) this; } public Criteria andDeptNameLessThanOrEqualTo(String value) { addCriterion("dept_name <=", value, "deptName"); return (Criteria) this; } public Criteria andDeptNameLike(String value) { addCriterion("dept_name like", value, "deptName"); return (Criteria) this; } public Criteria andDeptNameNotLike(String value) { addCriterion("dept_name not like", value, "deptName"); return (Criteria) this; } public Criteria andDeptNameIn(List<String> values) { addCriterion("dept_name in", values, "deptName"); return (Criteria) this; } public Criteria andDeptNameNotIn(List<String> values) { addCriterion("dept_name not in", values, "deptName"); return (Criteria) this; } public Criteria andDeptNameBetween(String value1, String value2) { addCriterion("dept_name between", value1, value2, "deptName"); return (Criteria) this; } public Criteria andDeptNameNotBetween(String value1, String value2) { addCriterion("dept_name not between", value1, value2, "deptName"); 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); } } }
package com.atguigu.crud.bean; public class Department { private Integer deptId; private String deptName; public Department() { super(); // TODO Auto-generated constructor stub } public Department(Integer deptId, String deptName) { super(); this.deptId = deptId; this.deptName = deptName; } public Integer getDeptId() { return deptId; } public void setDeptId(Integer deptId) { this.deptId = deptId; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName == null ? null : deptName.trim(); } }
Service層:
package com.atguigu.crud.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.atguigu.crud.bean.Department; import com.atguigu.crud.dao.DepartmentMapper; @Service public class DepartmentService { @Autowired private DepartmentMapper departmentMapper; public List<Department> getDepts() { // TODO Auto-generated method stub List<Department> list = departmentMapper.selectByExample(null); return list; } }
package com.atguigu.crud.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.atguigu.crud.bean.Employee; import com.atguigu.crud.bean.EmployeeExample; import com.atguigu.crud.bean.EmployeeExample.Criteria; import com.atguigu.crud.dao.EmployeeMapper; @Service public class EmployeeService { @Autowired EmployeeMapper employeeMapper; /** * 查詢全部員工 * @return */ public List<Employee> getAll() { // TODO Auto-generated method stub return employeeMapper.selectByExampleWithDept(null); } /** * 員工保存 * @param employee */ public void saveEmp(Employee employee) { // TODO Auto-generated method stub employeeMapper.insertSelective(employee); } /** * 檢驗用戶名是否可用 * * @param empName * @return true:表明當前姓名可用 fasle:不可用 */ public boolean checkUser(String empName) { // TODO Auto-generated method stub EmployeeExample example = new EmployeeExample(); Criteria criteria = example.createCriteria(); criteria.andEmpNameEqualTo(empName); long count = employeeMapper.countByExample(example); return count == 0; } /** * 按照員工id查詢員工 * @param id * @return */ public Employee getEmp(Integer id) { // TODO Auto-generated method stub Employee employee = employeeMapper.selectByPrimaryKey(id); return employee; } /** * 員工更新 * @param employee */ public void updateEmp(Employee employee) { // TODO Auto-generated method stub employeeMapper.updateByPrimaryKeySelective(employee); } /** * 員工刪除 * @param id */ public void deleteEmp(Integer id) { // TODO Auto-generated method stub employeeMapper.deleteByPrimaryKey(id); } public void deleteBatch(List<Integer> ids) { // TODO Auto-generated method stub EmployeeExample example = new EmployeeExample(); Criteria criteria = example.createCriteria(); //delete from xxx where emp_id in(1,2,3) criteria.andEmpIdIn(ids); employeeMapper.deleteByExample(example); } }
controller層:
package com.atguigu.crud.controller; import java.util.List; 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.atguigu.crud.bean.Department; import com.atguigu.crud.bean.Msg; import com.atguigu.crud.service.DepartmentService; /** * 處理和部門有關的請求 * @author lfy * */ @Controller public class DepartmentController { @Autowired private DepartmentService departmentService; /** * 返回全部的部門信息 */ @RequestMapping("/depts") @ResponseBody public Msg getDepts(){ //查出的全部部門信息 List<Department> list = departmentService.getDepts(); return Msg.success().add("depts", list); } }
package com.atguigu.crud.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.atguigu.crud.bean.Employee; import com.atguigu.crud.bean.Msg; import com.atguigu.crud.service.EmployeeService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; /** * 處理員工CRUD請求 * * @author lfy * */ @Controller public class EmployeeController { @Autowired EmployeeService employeeService; /** * 單個批量二合一 * 批量刪除:1-2-3 * 單個刪除:1 * * @param id * @return */ @ResponseBody @RequestMapping(value="/emp/{ids}",method=RequestMethod.DELETE) public Msg deleteEmp(@PathVariable("ids")String ids){ //批量刪除 if(ids.contains("-")){ List<Integer> del_ids = new ArrayList<>(); String[] str_ids = ids.split("-"); //組裝id的集合 for (String string : str_ids) { del_ids.add(Integer.parseInt(string)); } employeeService.deleteBatch(del_ids); }else{ Integer id = Integer.parseInt(ids); employeeService.deleteEmp(id); } return Msg.success(); } /** * 若是直接發送ajax=PUT形式的請求 * 封裝的數據 * Employee * [empId=1014, empName=null, gender=null, email=null, dId=null] * * 問題: * 請求體中有數據; * 可是Employee對象封裝不上; * update tbl_emp where emp_id = 1014; * * 緣由: * Tomcat: * 一、將請求體中的數據,封裝一個map。 * 二、request.getParameter("empName")就會從這個map中取值。 * 三、SpringMVC封裝POJO對象的時候。 * 會把POJO中每一個屬性的值,request.getParamter("email"); * AJAX發送PUT請求引起的血案: * PUT請求,請求體中的數據,request.getParameter("empName")拿不到 * Tomcat一看是PUT不會封裝請求體中的數據爲map,只有POST形式的請求才封裝請求體爲map * org.apache.catalina.connector.Request--parseParameters() (3111); * * protected String parseBodyMethods = "POST"; * if( !getConnector().isParseBodyMethod(getMethod()) ) { success = true; return; } * * * 解決方案; * 咱們要能支持直接發送PUT之類的請求還要封裝請求體中的數據 * 一、配置上HttpPutFormContentFilter; * 二、他的做用;將請求體中的數據解析包裝成一個map。 * 三、request被從新包裝,request.getParameter()被重寫,就會從本身封裝的map中取數據 * 員工更新方法 * @param employee * @return */ @ResponseBody @RequestMapping(value="/emp/{empId}",method=RequestMethod.PUT) public Msg saveEmp(Employee employee,HttpServletRequest request){ System.out.println("請求體中的值:"+request.getParameter("gender")); System.out.println("將要更新的員工數據:"+employee); employeeService.updateEmp(employee); return Msg.success() ; } /** * 根據id查詢員工 * @param id * @return */ @RequestMapping(value="/emp/{id}",method=RequestMethod.GET) @ResponseBody public Msg getEmp(@PathVariable("id")Integer id){ Employee employee = employeeService.getEmp(id); return Msg.success().add("emp", employee); } /** * 檢查用戶名是否可用 * @param empName * @return */ @ResponseBody @RequestMapping("/checkuser") public Msg checkuser(@RequestParam("empName")String empName){ //先判斷用戶名是不是合法的表達式; String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})"; if(!empName.matches(regx)){ return Msg.fail().add("va_msg", "用戶名必須是6-16位數字和字母的組合或者2-5位中文"); } //數據庫用戶名重複校驗 boolean b = employeeService.checkUser(empName); if(b){ return Msg.success(); }else{ return Msg.fail().add("va_msg", "用戶名不可用"); } } /** * 員工保存 * 一、支持JSR303校驗 * 二、導入Hibernate-Validator * * * @return */ @RequestMapping(value="/emp",method=RequestMethod.POST) @ResponseBody public Msg saveEmp(@Valid Employee employee,BindingResult result){ if(result.hasErrors()){ //校驗失敗,應該返回失敗,在模態框中顯示校驗失敗的錯誤信息 Map<String, Object> map = new HashMap<>(); List<FieldError> errors = result.getFieldErrors(); for (FieldError fieldError : errors) { System.out.println("錯誤的字段名:"+fieldError.getField()); System.out.println("錯誤信息:"+fieldError.getDefaultMessage()); map.put(fieldError.getField(), fieldError.getDefaultMessage()); } return Msg.fail().add("errorFields", map); }else{ employeeService.saveEmp(employee); return Msg.success(); } } /** * 導入jackson包。 * @param pn * @return */ @RequestMapping("/emps") @ResponseBody public Msg getEmpsWithJson( @RequestParam(value = "pn", defaultValue = "1") Integer pn) { // 這不是一個分頁查詢 // 引入PageHelper分頁插件 // 在查詢以前只須要調用,傳入頁碼,以及每頁的大小 PageHelper.startPage(pn, 5); // startPage後面緊跟的這個查詢就是一個分頁查詢 List<Employee> emps = employeeService.getAll(); // 使用pageInfo包裝查詢後的結果,只須要將pageInfo交給頁面就好了。 // 封裝了詳細的分頁信息,包括有咱們查詢出來的數據,傳入連續顯示的頁數 PageInfo page = new PageInfo(emps, 5); return Msg.success().add("pageInfo", page); } /** * 查詢員工數據(分頁查詢) * * @return */ // @RequestMapping("/emps") public String getEmps( @RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) { // 這不是一個分頁查詢; // 引入PageHelper分頁插件 // 在查詢以前只須要調用,傳入頁碼,以及每頁的大小 PageHelper.startPage(pn, 5); // startPage後面緊跟的這個查詢就是一個分頁查詢 List<Employee> emps = employeeService.getAll(); // 使用pageInfo包裝查詢後的結果,只須要將pageInfo交給頁面就好了。 // 封裝了詳細的分頁信息,包括有咱們查詢出來的數據,傳入連續顯示的頁數 PageInfo page = new PageInfo(emps, 5); model.addAttribute("pageInfo", page); return "list"; } }
測試類:
package com.atguigu.crud.test; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.atguigu.crud.bean.Employee; import com.github.pagehelper.PageInfo; /** * 使用Spring測試模塊提供的測試請求功能,測試curd請求的正確性 * Spring4測試的時候,須要servlet3.0的支持 * @author lfy * */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations = { "classpath:applicationContext.xml", "file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml" }) public class MvcTest { // 傳入Springmvc的ioc @Autowired WebApplicationContext context; // 虛擬mvc請求,獲取處處理結果。 MockMvc mockMvc; @Before public void initMokcMvc() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } @Test public void testPage() throws Exception { //模擬請求拿到返回值 MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn", "5")) .andReturn(); //請求成功之後,請求域中會有pageInfo;咱們能夠取出pageInfo進行驗證 MockHttpServletRequest request = result.getRequest(); PageInfo pi = (PageInfo) request.getAttribute("pageInfo"); System.out.println("當前頁碼:"+pi.getPageNum()); System.out.println("總頁碼:"+pi.getPages()); System.out.println("總記錄數:"+pi.getTotal()); System.out.println("在頁面須要連續顯示的頁碼"); int[] nums = pi.getNavigatepageNums(); for (int i : nums) { System.out.print(" "+i); } //獲取員工數據 List<Employee> list = pi.getList(); for (Employee employee : list) { System.out.println("ID:"+employee.getEmpId()+"==>Name:"+employee.getEmpName()); } } }
視圖層:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>員工列表</title> <% pageContext.setAttribute("APP_PATH", request.getContextPath()); %> <!-- web路徑: 不以/開始的相對路徑,找資源,以當前資源的路徑爲基準,常常容易出問題。 以/開始的相對路徑,找資源,以服務器的路徑爲標準(http://localhost:3306);須要加上項目名 http://localhost:3306/crud --> <script type="text/javascript" src="${APP_PATH }/static/js/jquery-1.12.4.min.js"></script> <link href="${APP_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet"> <script src="${APP_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> </head> <body> <!-- 員工修改的模態框 --> <div class="modal fade" id="empUpdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title">員工修改</h4> </div> <div class="modal-body"> <form class="form-horizontal"> <div class="form-group"> <label class="col-sm-2 control-label">empName</label> <div class="col-sm-10"> <p class="form-control-static" id="empName_update_static"></p> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">email</label> <div class="col-sm-10"> <input type="text" name="email" class="form-control" id="email_update_input" placeholder="email@atguigu.com"> <span class="help-block"></span> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">gender</label> <div class="col-sm-10"> <label class="radio-inline"> <input type="radio" name="gender" id="gender1_update_input" value="M" checked="checked"> 男 </label> <label class="radio-inline"> <input type="radio" name="gender" id="gender2_update_input" value="F"> 女 </label> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">deptName</label> <div class="col-sm-4"> <!-- 部門提交部門id便可 --> <select class="form-control" name="dId"> </select> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button> <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button> </div> </div> </div> </div> <!-- 員工添加的模態框 --> <div class="modal fade" id="empAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="myModalLabel">員工添加</h4> </div> <div class="modal-body"> <form class="form-horizontal"> <div class="form-group"> <label class="col-sm-2 control-label">empName</label> <div class="col-sm-10"> <input type="text" name="empName" class="form-control" id="empName_add_input" placeholder="empName"> <span class="help-block"></span> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">email</label> <div class="col-sm-10"> <input type="text" name="email" class="form-control" id="email_add_input" placeholder="email@atguigu.com"> <span class="help-block"></span> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">gender</label> <div class="col-sm-10"> <label class="radio-inline"> <input type="radio" name="gender" id="gender1_add_input" value="M" checked="checked"> 男 </label> <label class="radio-inline"> <input type="radio" name="gender" id="gender2_add_input" value="F"> 女 </label> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">deptName</label> <div class="col-sm-4"> <!-- 部門提交部門id便可 --> <select class="form-control" name="dId"> </select> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button> <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button> </div> </div> </div> </div> <!-- 搭建顯示頁面 --> <div class="container"> <!-- 標題 --> <div class="row"> <div class="col-md-12"> <h1>SSM-CRUD</h1> </div> </div> <!-- 按鈕 --> <div class="row"> <div class="col-md-4 col-md-offset-8"> <button class="btn btn-primary" id="emp_add_modal_btn">新增</button> <button class="btn btn-danger" id="emp_delete_all_btn">刪除</button> </div> </div> <!-- 顯示錶格數據 --> <div class="row"> <div class="col-md-12"> <table class="table table-hover" id="emps_table"> <thead> <tr> <th> <input type="checkbox" id="check_all"/> </th> <th>#</th> <th>empName</th> <th>gender</th> <th>email</th> <th>deptName</th> <th>操做</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <!-- 顯示分頁信息 --> <div class="row"> <!--分頁文字信息 --> <div class="col-md-6" id="page_info_area"></div> <!-- 分頁條信息 --> <div class="col-md-6" id="page_nav_area"> </div> </div> </div> <script type="text/javascript"> var totalRecord,currentPage; //一、頁面加載完成之後,直接去發送ajax請求,要到分頁數據 $(function(){ //去首頁 to_page(1); }); function to_page(pn){ $.ajax({ url:"${APP_PATH}/emps", data:"pn="+pn, type:"GET", success:function(result){ //console.log(result); //一、解析並顯示員工數據 build_emps_table(result); //二、解析並顯示分頁信息 build_page_info(result); //三、解析顯示分頁條數據 build_page_nav(result); } }); } function build_emps_table(result){ //清空table表格 $("#emps_table tbody").empty(); var emps = result.extend.pageInfo.list; $.each(emps,function(index,item){ var checkBoxTd = $("<td><input type='checkbox' class='check_item'/></td>"); var empIdTd = $("<td></td>").append(item.empId); var empNameTd = $("<td></td>").append(item.empName); var genderTd = $("<td></td>").append(item.gender=='M'?"男":"女"); var emailTd = $("<td></td>").append(item.email); var deptNameTd = $("<td></td>").append(item.department.deptName); /** <button class=""> <span class="" aria-hidden="true"></span> 編輯 </button> */ var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn") .append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("編輯"); //爲編輯按鈕添加一個自定義的屬性,來表示當前員工id editBtn.attr("edit-id",item.empId); var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn") .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("刪除"); //爲刪除按鈕添加一個自定義的屬性來表示當前刪除的員工id delBtn.attr("del-id",item.empId); var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn); //var delBtn = //append方法執行完成之後仍是返回原來的元素 $("<tr></tr>").append(checkBoxTd) .append(empIdTd) .append(empNameTd) .append(genderTd) .append(emailTd) .append(deptNameTd) .append(btnTd) .appendTo("#emps_table tbody"); }); } //解析顯示分頁信息 function build_page_info(result){ $("#page_info_area").empty(); $("#page_info_area").append("當前"+result.extend.pageInfo.pageNum+"頁,總"+ result.extend.pageInfo.pages+"頁,總"+ result.extend.pageInfo.total+"條記錄"); totalRecord = result.extend.pageInfo.total; currentPage = result.extend.pageInfo.pageNum; } //解析顯示分頁條,點擊分頁要能去下一頁.... function build_page_nav(result){ //page_nav_area $("#page_nav_area").empty(); var ul = $("<ul></ul>").addClass("pagination"); //構建元素 var firstPageLi = $("<li></li>").append($("<a></a>").append("首頁").attr("href","#")); var prePageLi = $("<li></li>").append($("<a></a>").append("«")); if(result.extend.pageInfo.hasPreviousPage == false){ firstPageLi.addClass("disabled"); prePageLi.addClass("disabled"); }else{ //爲元素添加點擊翻頁的事件 firstPageLi.click(function(){ to_page(1); }); prePageLi.click(function(){ to_page(result.extend.pageInfo.pageNum -1); }); } var nextPageLi = $("<li></li>").append($("<a></a>").append("»")); var lastPageLi = $("<li></li>").append($("<a></a>").append("末頁").attr("href","#")); if(result.extend.pageInfo.hasNextPage == false){ nextPageLi.addClass("disabled"); lastPageLi.addClass("disabled"); }else{ nextPageLi.click(function(){ to_page(result.extend.pageInfo.pageNum +1); }); lastPageLi.click(function(){ to_page(result.extend.pageInfo.pages); }); } //添加首頁和前一頁 的提示 ul.append(firstPageLi).append(prePageLi); //1,2,3遍歷給ul中添加頁碼提示 $.each(result.extend.pageInfo.navigatepageNums,function(index,item){ var numLi = $("<li></li>").append($("<a></a>").append(item)); if(result.extend.pageInfo.pageNum == item){ numLi.addClass("active"); } numLi.click(function(){ to_page(item); }); ul.append(numLi); }); //添加下一頁和末頁 的提示 ul.append(nextPageLi).append(lastPageLi); //把ul加入到nav var navEle = $("<nav></nav>").append(ul); navEle.appendTo("#page_nav_area"); } //清空表單樣式及內容 function reset_form(ele){ $(ele)[0].reset(); //清空表單樣式 $(ele).find("*").removeClass("has-error has-success"); $(ele).find(".help-block").text(""); } //點擊新增按鈕彈出模態框。 $("#emp_add_modal_btn").click(function(){ //清除表單數據(表單完整重置(表單的數據,表單的樣式)) reset_form("#empAddModal form"); //s$("")[0].reset(); //發送ajax請求,查出部門信息,顯示在下拉列表中 getDepts("#empAddModal select"); //彈出模態框 $("#empAddModal").modal({ backdrop:"static" }); }); //查出全部的部門信息並顯示在下拉列表中 function getDepts(ele){ //清空以前下拉列表的值 $(ele).empty(); $.ajax({ url:"${APP_PATH}/depts", type:"GET", success:function(result){ //{"code":100,"msg":"處理成功!", //"extend":{"depts":[{"deptId":1,"deptName":"開發部"},{"deptId":2,"deptName":"測試部"}]}} //console.log(result); //顯示部門信息在下拉列表中 //$("#empAddModal select").append("") $.each(result.extend.depts,function(){ var optionEle = $("<option></option>").append(this.deptName).attr("value",this.deptId); optionEle.appendTo(ele); }); } }); } //校驗表單數據 function validate_add_form(){ //一、拿到要校驗的數據,使用正則表達式 var empName = $("#empName_add_input").val(); var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/; if(!regName.test(empName)){ //alert("用戶名能夠是2-5位中文或者6-16位英文和數字的組合"); show_validate_msg("#empName_add_input", "error", "用戶名能夠是2-5位中文或者6-16位英文和數字的組合"); return false; }else{ show_validate_msg("#empName_add_input", "success", ""); }; //二、校驗郵箱信息 var email = $("#email_add_input").val(); var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/; if(!regEmail.test(email)){ //alert("郵箱格式不正確"); //應該清空這個元素以前的樣式 show_validate_msg("#email_add_input", "error", "郵箱格式不正確"); /* $("#email_add_input").parent().addClass("has-error"); $("#email_add_input").next("span").text("郵箱格式不正確"); */ return false; }else{ show_validate_msg("#email_add_input", "success", ""); } return true; } //顯示校驗結果的提示信息 function show_validate_msg(ele,status,msg){ //清除當前元素的校驗狀態 $(ele).parent().removeClass("has-success has-error"); $(ele).next("span").text(""); if("success"==status){ $(ele).parent().addClass("has-success"); $(ele).next("span").text(msg); }else if("error" == status){ $(ele).parent().addClass("has-error"); $(ele).next("span").text(msg); } } //校驗用戶名是否可用 $("#empName_add_input").change(function(){ //發送ajax請求校驗用戶名是否可用 var empName = this.value; $.ajax({ url:"${APP_PATH}/checkuser", data:"empName="+empName, type:"POST", success:function(result){ if(result.code==100){ show_validate_msg("#empName_add_input","success","用戶名可用"); $("#emp_save_btn").attr("ajax-va","success"); }else{ show_validate_msg("#empName_add_input","error",result.extend.va_msg); $("#emp_save_btn").attr("ajax-va","error"); } } }); }); //點擊保存,保存員工。 $("#emp_save_btn").click(function(){ //一、模態框中填寫的表單數據提交給服務器進行保存 //一、先對要提交給服務器的數據進行校驗 if(!validate_add_form()){ return false; }; //一、判斷以前的ajax用戶名校驗是否成功。若是成功。 if($(this).attr("ajax-va")=="error"){ return false; } //二、發送ajax請求保存員工 $.ajax({ url:"${APP_PATH}/emp", type:"POST", data:$("#empAddModal form").serialize(), success:function(result){ //alert(result.msg); if(result.code == 100){ //員工保存成功; //一、關閉模態框 $("#empAddModal").modal('hide'); //二、來到最後一頁,顯示剛纔保存的數據 //發送ajax請求顯示最後一頁數據便可 to_page(totalRecord); }else{ //顯示失敗信息 //console.log(result); //有哪一個字段的錯誤信息就顯示哪一個字段的; if(undefined != result.extend.errorFields.email){ //顯示郵箱錯誤信息 show_validate_msg("#email_add_input", "error", result.extend.errorFields.email); } if(undefined != result.extend.errorFields.empName){ //顯示員工名字的錯誤信息 show_validate_msg("#empName_add_input", "error", result.extend.errorFields.empName); } } } }); }); //一、咱們是按鈕建立以前就綁定了click,因此綁定不上。 //1)、能夠在建立按鈕的時候綁定。 2)、綁定點擊.live() //jquery新版沒有live,使用on進行替代 $(document).on("click",".edit_btn",function(){ //alert("edit"); //一、查出部門信息,並顯示部門列表 getDepts("#empUpdateModal select"); //二、查出員工信息,顯示員工信息 getEmp($(this).attr("edit-id")); //三、把員工的id傳遞給模態框的更新按鈕 $("#emp_update_btn").attr("edit-id",$(this).attr("edit-id")); $("#empUpdateModal").modal({ backdrop:"static" }); }); function getEmp(id){ $.ajax({ url:"${APP_PATH}/emp/"+id, type:"GET", success:function(result){ //console.log(result); var empData = result.extend.emp; $("#empName_update_static").text(empData.empName); $("#email_update_input").val(empData.email); $("#empUpdateModal input[name=gender]").val([empData.gender]); $("#empUpdateModal select").val([empData.dId]); } }); } //點擊更新,更新員工信息 $("#emp_update_btn").click(function(){ //驗證郵箱是否合法 //一、校驗郵箱信息 var email = $("#email_update_input").val(); var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/; if(!regEmail.test(email)){ show_validate_msg("#email_update_input", "error", "郵箱格式不正確"); return false; }else{ show_validate_msg("#email_update_input", "success", ""); } //二、發送ajax請求保存更新的員工數據 $.ajax({ url:"${APP_PATH}/emp/"+$(this).attr("edit-id"), type:"PUT", data:$("#empUpdateModal form").serialize(), success:function(result){ //alert(result.msg); //一、關閉對話框 $("#empUpdateModal").modal("hide"); //二、回到本頁面 to_page(currentPage); } }); }); //單個刪除 $(document).on("click",".delete_btn",function(){ //一、彈出是否確認刪除對話框 var empName = $(this).parents("tr").find("td:eq(2)").text(); var empId = $(this).attr("del-id"); //alert($(this).parents("tr").find("td:eq(1)").text()); if(confirm("確認刪除【"+empName+"】嗎?")){ //確認,發送ajax請求刪除便可 $.ajax({ url:"${APP_PATH}/emp/"+empId, type:"DELETE", success:function(result){ alert(result.msg); //回到本頁 to_page(currentPage); } }); } }); //完成全選/全不選功能 $("#check_all").click(function(){ //attr獲取checked是undefined; //咱們這些dom原生的屬性;attr獲取自定義屬性的值; //prop修改和讀取dom原生屬性的值 $(".check_item").prop("checked",$(this).prop("checked")); }); //check_item $(document).on("click",".check_item",function(){ //判斷當前選擇中的元素是否5個 var flag = $(".check_item:checked").length==$(".check_item").length; $("#check_all").prop("checked",flag); }); //點擊所有刪除,就批量刪除 $("#emp_delete_all_btn").click(function(){ // var empNames = ""; var del_idstr = ""; $.each($(".check_item:checked"),function(){ //this empNames += $(this).parents("tr").find("td:eq(2)").text()+","; //組裝員工id字符串 del_idstr += $(this).parents("tr").find("td:eq(1)").text()+"-"; }); //去除empNames多餘的, empNames = empNames.substring(0, empNames.length-1); //去除刪除的id多餘的- del_idstr = del_idstr.substring(0, del_idstr.length-1); if(confirm("確認刪除【"+empNames+"】嗎?")){ //發送ajax請求刪除 $.ajax({ url:"${APP_PATH}/emp/"+del_idstr, type:"DELETE", success:function(result){ alert(result.msg); //回到當前頁面 to_page(currentPage); } }); } }); </script> </body> </html>
報錯緣由:原jdk和Tomcat的el-api架包沒有ElManage
解決方法:下載el-api3.0放到Tomcat的lib目錄下或者jdk目錄下(別放在jdk下,跑springboot會出問題)
失敗緣由:Tomcat只是封裝Post請求的參數
解決方法:在web,xml文件中添加過濾器