學習mybaits簡單增刪改查例子記錄 css
此整理是學習視頻後的視頻內容整理,後半段尚未整理html
最後項目目錄以下圖 :前端
數據庫表sql 爲 :java
USE `ssm`; /*Table structure for table `tbl_dept` */ DROP TABLE IF EXISTS `tbl_dept`; CREATE TABLE `tbl_dept` ( `dept_id` int(11) NOT NULL AUTO_INCREMENT, `dept_name` varchar(255) NOT NULL, PRIMARY KEY (`dept_id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; /*Table structure for table `tbl_emp` */ DROP TABLE IF EXISTS `tbl_emp`; CREATE TABLE `tbl_emp` ( `emp_id` int(11) NOT NULL AUTO_INCREMENT, `emp_name` varchar(255) NOT NULL, `gender` char(1) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `d_id` int(11) DEFAULT NULL, PRIMARY KEY (`emp_id`), KEY `fk_emp_dept` (`d_id`), CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`) ON DELETE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=1001 DEFAULT CHARSET=utf8;
建立maven項目 目錄結構 ssm-crud 引入須要用到jar包 pom文件爲 :mysql
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lixuchun</groupId> <artifactId>ssm-crud</artifactId> <packaging>pom</packaging> <version>0.0.1-SNAPSHOT</version> <name>ssm-crud Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- 引入pagehelper分頁插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.0.0</version> </dependency> <!-- 引入springmvc spring 包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- spring jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.7.RELEASE</version> <scope>test</scope> </dependency> <!-- spring aop --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- mybaits --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- 數據庫鏈接池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.2</version> </dependency> <!-- 數據庫驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> </dependency> <!-- jstl servlet-api --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>ssm-crud</finalName> </build> <modules> <module>?</module> </modules> </project>
修改web.xml 文件 最後 web.xml文件爲jquery
<?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> <!-- 三、字符編碼過濾器,必定要放在全部過濾器以前 forceRequestEncoding response 分別設置響應請求編碼 --> <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>
添加springmvc配置文件,對應名稱爲web.xml 中 dispatcherServlet 都加上 -servlet dispatcherServlet-servlet.xmlgit
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <!-- SpringMvc的配置文件,包含網站跳轉文件的配置 --> <context:component-scan base-package="com.lixuchun" use-default-filters="false"> <!-- -只掃描控制器 --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- ,配置視圖解析器 如何把 handler 方法返回值解析爲實際的物理視圖,jsp路徑的前綴和後綴 --> <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更高級的一些功能,JRS303校驗,ajax請求..映射動態請求 --> <mvc:annotation-driven></mvc:annotation-driven> </beans>
配置spring 添加applicationContext.xml配置文件github
<?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.lixuchun"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <context:property-placeholder location="classpath:dbconfig.properties"/> <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="dataSource" ref="pooledDataSource"></property> <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.lixuchun.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 id="txPoint" expression="execution(* com.lixuchun.crud.service..*(..))"/> <!-- 配置事務加強 指明切入點--> <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> </beans>
建立數據庫配置文件dbconfig.propertiesweb
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?characterEncoding=utf8&useSSL=true jdbc.driverClass=com.mysql.jdbc.Driver jdbc.username=root jdbc.password=101022
建立mybatis-config.xml ajax
<?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.lixuchun.crud.bean" /> </typeAliases> <!-- mybaits 分頁插件 --> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <property name="reasonable" value="true"/> </plugin> </plugins> </configuration>
建立 entity包 com.lixuchun.crud.bean 建立bean
Department
package com.lixuchun.crud.bean; public class Department { private Integer deptId; private String deptName; public Department() { super(); } 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(); } }
Employee
package com.lixuchun.crud.bean; public class Employee { private Integer empId; private String empName; private String gender; private String email; private Integer 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; } // 但願查詢員工時候 部門信息也有顯示 private Department department; 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; } }
建立通用返回類Message
package com.lixuchun.crud.bean; import java.util.HashMap; import java.util.Map; /** * 通用返回類 * @author UPC * */ public class Message { /** * 狀態碼 100 成功 200失敗 */ private int code; // 提示信息 private String msg; private Map<String, Object> extend = new HashMap<String, Object>(); public int getCode() { return code; } public static Message success() { Message msg = new Message(); msg.setCode(100); msg.setMsg("success"); return msg; } public static Message fail() { Message msg = new Message(); msg.setCode(200); msg.setMsg("fail"); return msg; } public Message add(String key, Object value) { this.getExtend().put(key, value); return this; } 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; } }
建立dao 包 com.lixuchun.crud.dao
DepartmentMapper
package com.lixuchun.crud.dao; import com.lixuchun.crud.bean.Department; import com.lixuchun.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); }
EmployeeMapper
package com.lixuchun.crud.dao; import com.lixuchun.crud.bean.Employee; import com.lixuchun.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); }
建立dao實現mapper
DepartmentMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.lixuchun.crud.dao.DepartmentMapper"> <resultMap id="BaseResultMap" type="com.lixuchun.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.lixuchun.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.lixuchun.crud.bean.DepartmentExample"> delete from tbl_dept <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" parameterType="com.lixuchun.crud.bean.Department"> insert into tbl_dept (dept_id, dept_name) values (#{deptId,jdbcType=INTEGER}, #{deptName,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.lixuchun.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.lixuchun.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.lixuchun.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.lixuchun.crud.bean.Department"> update tbl_dept set dept_name = #{deptName,jdbcType=VARCHAR} where dept_id = #{deptId,jdbcType=INTEGER} </update> </mapper>
EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.lixuchun.crud.dao.EmployeeMapper"> <resultMap id="BaseResultMap" type="com.lixuchun.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.lixuchun.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.lixuchun.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="With_Dept_Column_List"> e.emp_id, e.emp_name, e.gender, e.email, e.d_id, d.dept_id, d.dept_name </sql> <!-- List selectByExampleWithDept selectByPrimaryKeyWithDept --> <!-- 查詢帶部門 --> <select id="selectByExampleWithDept" resultMap="WithDeptResultMap"> select <if test="distinct"> distinct </if> <include refid="With_Dept_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="With_Dept_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.lixuchun.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.lixuchun.crud.bean.EmployeeExample"> delete from tbl_emp <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" parameterType="com.lixuchun.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.lixuchun.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.lixuchun.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.lixuchun.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.lixuchun.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>
在src/test/java 下建立mappertest 文件測試
TestMapper
import java.util.List; 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.lixuchun.crud.bean.Employee; import com.lixuchun.crud.dao.DepartmentMapper; import com.lixuchun.crud.dao.EmployeeMapper; import com.lixuchun.crud.service.EmployeeService; /** * 用spring 測試類測試 * @author UPC * 1.導入springTest模塊 * 2. * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext.xml"}) public class TestMapper { @Autowired DepartmentMapper departmentMapper; @Autowired EmployeeMapper employeeMapper; @Autowired SqlSession sqlSession; @Autowired EmployeeService employeeService; @Test public void testCRUD() { // 插入點 /* departmentMapper.insertSelective(new Department(null, "開發部")); departmentMapper.insertSelective(new Department(null, "測試部")); */ // 生成一些員工數據 //employeeMapper.insertSelective(new Employee(null, "jack", "M", "jack@mic.com", 1)); // 批量插入多個員工-- 使用能夠執行批量操做的sqlsession // 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 + "@mic.com", 1)); // } // System.out.println("批量完成!"); List<Employee> emps = employeeService.getAll(); for (Employee emp : emps) { System.out.println(emp.getEmpName()); } } }
建立 test 包 com.lixuchun.crud.test
mvc_test
package com.lixuchun.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.github.pagehelper.PageInfo; import com.lixuchun.crud.bean.Employee; /** * 使用Spring測試木塊提供的測試請求功能,測試crud請求的正確性 * Spring4測試的時候,須要servlet3.0的支持 * @author wp * */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations={"classpath:applicationContext.xml","file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml"}) public class MVC_TEST { //傳入Springmvc的ioc @Autowired WebApplicationContext context; //虛擬mvc請求,獲取處處理結果 MockMvc movkMVC; //junit的before 在每次使用以前都要初始化 @Before public void initMockMvc(){ movkMVC=MockMvcBuilders.webAppContextSetup(context).build(); } @Test public void testPage() throws Exception{ //模擬請求拿到返回值 MvcResult result = movkMVC.perform(MockMvcRequestBuilders.get("/emps").param("pn", "3")).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.println(" "+i); } //獲取員工數據 List<Employee> list= pi.getList(); for(Employee employee : list ){ System.out.println("ID:" +employee.getEmpId()+"==>Name:"+employee.getEmpName()); } } }
建立com.lixuchun.crud.service 包
EmployeeService
package com.lixuchun.crud.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.lixuchun.crud.bean.Employee; import com.lixuchun.crud.dao.EmployeeMapper; @Service public class EmployeeService { @Autowired EmployeeMapper employeeMapper; public List<Employee> getAll() { return employeeMapper.selectByExampleWithDept(null); } }
建立com.lixuchun.crud.controller 包
EmployeeController
package com.lixuchun.crud.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.lixuchun.crud.bean.Employee; import com.lixuchun.crud.bean.Message; import com.lixuchun.crud.service.EmployeeService; /** * 員工處理 * @author UPC * */ @Controller public class EmployeeController { @Autowired EmployeeService employeeService; @RequestMapping("/emps") public String getEmployees(@RequestParam(value="pn", defaultValue="1") Integer pn, Model model) { // 不是一個分頁查詢 // 引入分頁插件 pageNum, pageSize PageHelper.startPage(pn, 5); // startPage 後緊跟這個查詢就是分頁查詢 List<Employee> emps = employeeService.getAll(); // 使用pageInfo包裝查詢後的結果, 講pageinfo交給頁面就ok // 封裝了詳細的分頁信息 包括咱們查詢出來的數據 // 5爲連續顯示頁數 PageInfo pageInfo = new PageInfo(emps, 5); model.addAttribute("pageInfo", pageInfo); return "list"; } // @RequestMapping("/emps") // public String getEmps(@RequestParam(value="pn" ,defaultValue="1")Integer pn, Model model){ //傳入當前頁面,若是沒有傳則默認爲1 // // //引入PageHelper分頁插件 // //在查詢以前只須要調用,傳入頁碼,以及分頁每一頁的大小 // PageHelper.startPage(pn, 5); // //startPage後面緊跟的這個查詢就是一個分頁查詢 // List<Employee> emps =employeeService.getAll(); // //使用pageInfo包裝查詢後的信息,只須要將pageinfo交給頁面就好了。 // //封裝了詳細的分頁信息,包括有咱們查詢出來的數據,傳入:連續顯示的頁數 // PageInfo page=new PageInfo(emps,5); //5表示要連續顯示的頁數 // model.addAttribute("pageInfo",page); // return "list"; // } /** * ResponseBody 使用須要jackson包 * @param pn * @param model * @return */ @RequestMapping("/empsWithJson") @ResponseBody public Message getEmpsWithJson( @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); //5表示要連續顯示的頁數 return Message.success().add("pageInfo", page); } }
在webapp下引入bootstrap插件包, 在WEB-INF 下建立view目錄 建立list.jsp頁面而且引用bootstrap插件
目錄結構爲 :
list.jsp 文件之有顯示分頁功能 其他沒有寫 後續可能會完善
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>員工列表</title> <% pageContext.setAttribute("APP_PATH", request.getContextPath()); %> <link href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <!-- 展現頁面 --> <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">新增</button> <button class="btn btn-danger">刪除</button> </div> </div> <!-- 表格 --> <div class="row"> <div class="col-md-12"> <table class="table table-hover"> <tr> <th>#</th> <th>empName</th> <th>gender</th> <th>email</th> <th>deptName</th> <th>操做</th> </tr> <c:forEach items="${pageInfo.list}" var="emp"> <tr> <th>${emp.empId}</th> <th>${emp.empName}</th> <th>${emp.gender=="M"?"男":"女"}</th> <!-- M則顯示男,不然顯示女 --> <th>${emp.email}</th> <th>${emp.department.deptName}</th> <th> <button class="btn btn-primary btn-sm"> <span class="glyphicon glyph icon-pencil"></span> 編輯 </button> <button class="btn btn-danger btn-sm"> <span class="glyphicon glyphicon-trash"></span> 刪除 </button> </th> </tr> </c:forEach> </table> </div> </div> <!-- 分頁組件 --> <div class="row"> <!-- 分頁信息 --> <div class="col-md-6"> 當前${pageInfo.pageNum}頁, 總${pageInfo.pages }頁, 總共${pageInfo.total}條數據 </div > <!-- 分頁條信息 --> <div class="col-md-6"> <nav aria-label="Page navigation"> <ul class="pagination"> <li><a href="${APP_PATH }/emps?pn=1">首頁</a></li> <c:if test="${pageInfo.hasPreviousPage}"> <li> <a href="${APP_PATH }/emps?pn=${pageInfo.pageNum - 1}" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> </c:if> <c:forEach items="${pageInfo.navigatepageNums }" var="page_Num"> <c:if test="${page_Num == pageInfo.pageNum }"> <li class="active"><a href="#">${page_Num}</a></li> </c:if> <c:if test="${page_Num != pageInfo.pageNum }"> <li><a href="${APP_PATH }/emps?pn=${page_Num}">${page_Num}</a></li> </c:if> </c:forEach> <c:if test="${pageInfo.hasNextPage}"> <li> <a href="${APP_PATH }/emps?pn=${pageInfo.pageNum + 1}" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </c:if> <li><a href="${APP_PATH }/emps?pn=${pageInfo.pages}">末頁</a></li> </ul> </nav> </div> </div> </div> <script src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/jquery-3.1.1.min.js"></script> <script src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script> </body> </html>
mybatis提供反向工程 自動生成mapper.xml功能
參考 http://www.mybatis.org/generator/configreference/xmlconfig.html
在 /ssm-crud/目錄下建立 MybatisGeneration.xml 文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="DB2Tables" targetRuntime="MyBatis3"> <!-- 去除註釋 --> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- 配置數據庫鏈接 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/ssm" userId="root" password="101022"> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 指定javabean生成的位置 --> <javaModelGenerator targetPackage= "com.lixuchun.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.lixuchun.crud.dao" targetProject=".\src\main\java" > <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 指定每一個表的生成策略 --> <table tableName="tbl_emp" domainObjectName="Employee"></table> <table tableName="tbl_dept" domainObjectName="Department"></table> </context> </generatorConfiguration>
建立 /ssm-crud/src/main/java/com/lixuchun/crud/test/MybatisGenerator.java
package com.lixuchun.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 MybatisGenerator { public static void main(String[] args) throws Exception { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("MybatisGeneration.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.xml文件 內容須要本身整理過濾
最後整個項目部署到tomcat中
訪問localhost:8081/ssm-crud/emps 就能夠進行訪問 出現下圖則訪問建立成功
此整理是學習視頻後的視頻內容整理,後半段尚未整理
網易雲課堂 SSM高級整合視頻 地址 : http://study.163.com/course/courseMain.htm?courseId=1003862031 很是好的視頻教程
項目源碼 前半段 https://pan.baidu.com/s/1hrPvZAg_dR2lMd6SpOLy9w
歡迎留言指正