4、spring+springMVC+mybaits+idea+maven

4、spring+springMVC+mybaits+idea+maven

1、构建项目结构如下

 

2、构建项目中的pom.xml文件中的依赖资源,里面包含ajax和分页插件的依赖哦

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 
  3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5   <modelVersion>4.0.0</modelVersion>
  6 
  7   <groupId>com</groupId>
  8   <artifactId>ssm_day45_01</artifactId>
  9   <version>1.0-SNAPSHOT</version>
 10   <packaging>war</packaging>
 11 
 12   <name>ssm_day45_01 Maven Webapp</name>
 13   <!-- FIXME change it to the project"s website -->
 14   <url>http://www.example.com</url>
 15 
 16   <properties>
 17     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 18     <maven.compiler.source>1.7</maven.compiler.source>
 19     <maven.compiler.target>1.7</maven.compiler.target>
 20   </properties>
 21 
 22   <dependencies>
 23     <dependency>
 24       <groupId>junit</groupId>
 25       <artifactId>junit</artifactId>
 26       <version>4.11</version>
 27     </dependency>
 28 
 29 
 30     <!--1 https://mvnrepository.com/artifact/org.springframework/spring-beans -->
 31     <dependency>
 32       <groupId>org.springframework</groupId>
 33       <artifactId>spring-beans</artifactId>
 34       <version>4.3.6.RELEASE</version>
 35     </dependency>
 36 
 37 
 38     <!--2 https://mvnrepository.com/artifact/org.springframework/spring-context -->
 39     <dependency>
 40       <groupId>org.springframework</groupId>
 41       <artifactId>spring-context</artifactId>
 42       <version>4.3.6.RELEASE</version>
 43     </dependency>
 44 
 45 
 46     <!-- 3https://mvnrepository.com/artifact/org.springframework/spring-core -->
 47     <dependency>
 48       <groupId>org.springframework</groupId>
 49       <artifactId>spring-core</artifactId>
 50       <version>4.3.6.RELEASE</version>
 51     </dependency>
 52 
 53 
 54     <!--4 https://mvnrepository.com/artifact/org.springframework/spring-expression -->
 55     <dependency>
 56       <groupId>org.springframework</groupId>
 57       <artifactId>spring-expression</artifactId>
 58       <version>4.3.6.RELEASE</version>
 59     </dependency>
 60 
 61 
 62     <!--5 https://mvnrepository.com/artifact/org.springframework/spring-aop -->
 63     <dependency>
 64       <groupId>org.springframework</groupId>
 65       <artifactId>spring-aop</artifactId>
 66       <version>4.3.6.RELEASE</version>
 67     </dependency>
 68 
 69 
 70     <!--6 https://mvnrepository.com/artifact/aopalliance/aopalliance -->
 71     <dependency>
 72       <groupId>aopalliance</groupId>
 73       <artifactId>aopalliance</artifactId>
 74       <version>1.0</version>
 75     </dependency>
 76 
 77 
 78     <!--7 https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
 79     <dependency>
 80       <groupId>org.aspectj</groupId>
 81       <artifactId>aspectjweaver</artifactId>
 82       <version>1.8.10</version>
 83     </dependency>
 84 
 85 
 86     <!--8 https://mvnrepository.com/artifact/log4j/log4j -->
 87     <dependency>
 88       <groupId>log4j</groupId>
 89       <artifactId>log4j</artifactId>
 90       <version>1.2.17</version>
 91     </dependency>
 92 
 93 
 94     <!--9 https://mvnrepository.com/artifact/commons-logging/commons-logging -->
 95     <dependency>
 96       <groupId>commons-logging</groupId>
 97       <artifactId>commons-logging</artifactId>
 98       <version>1.2</version>
 99     </dependency>
100 
101 
102     <!--10 https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
103     <dependency>
104       <groupId>org.springframework</groupId>
105       <artifactId>spring-jdbc</artifactId>
106       <version>4.3.6.RELEASE</version>
107     </dependency>
108 
109 
110     <!--11 https://mvnrepository.com/artifact/org.springframework/spring-orm -->
111     <dependency>
112       <groupId>org.springframework</groupId>
113       <artifactId>spring-orm</artifactId>
114       <version>4.3.6.RELEASE</version>
115     </dependency>
116 
117 
118     <!--12 https://mvnrepository.com/artifact/org.springframework/spring-tx -->
119     <dependency>
120       <groupId>org.springframework</groupId>
121       <artifactId>spring-tx</artifactId>
122       <version>4.3.6.RELEASE</version>
123     </dependency>
124 
125 
126     <!--13 https://mvnrepository.com/artifact/org.springframework/spring-web -->
127     <dependency>
128       <groupId>org.springframework</groupId>
129       <artifactId>spring-web</artifactId>
130       <version>4.3.6.RELEASE</version>
131     </dependency>
132 
133 
134     <!--14 https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
135     <dependency>
136       <groupId>org.springframework</groupId>
137       <artifactId>spring-webmvc</artifactId>
138       <version>4.3.6.RELEASE</version>
139     </dependency>
140 
141 
142     <!--15 https://mvnrepository.com/artifact/org.mybatis/mybatis -->
143     <dependency>
144       <groupId>org.mybatis</groupId>
145       <artifactId>mybatis</artifactId>
146       <version>3.4.6</version>
147     </dependency>
148 
149 
150     <!--16 https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
151     <dependency>
152       <groupId>mysql</groupId>
153       <artifactId>mysql-connector-java</artifactId>
154       <version>5.1.38</version>
155     </dependency>
156 
157 
158     <!--17 https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
159     <dependency>
160       <groupId>org.mybatis</groupId>
161       <artifactId>mybatis-spring</artifactId>
162       <version>1.3.2</version>
163     </dependency>
164 
165     <!--18 https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
166     <dependency>
167       <groupId>javax.servlet</groupId>
168       <artifactId>javax.servlet-api</artifactId>
169       <version>3.1.0</version>
170     </dependency>
171 
172     <!--19 https://mvnrepository.com/artifact/javax.servlet/jstl -->
173     <dependency>
174       <groupId>javax.servlet</groupId>
175       <artifactId>jstl</artifactId>
176       <version>1.2</version>
177     </dependency>
178 
179 
180     <!--20 https://mvnrepository.com/artifact/taglibs/standard -->
181     <dependency>
182       <groupId>taglibs</groupId>
183       <artifactId>standard</artifactId>
184       <version>1.1.2</version>
185     </dependency>
186 
187     <!--文件上传使用的jar-->
188     <!--21 https://mvnrepository.com/artifact/commons-io/commons-io -->
189     <dependency>
190       <groupId>commons-io</groupId>
191       <artifactId>commons-io</artifactId>
192       <version>2.4</version>
193     </dependency>
194     <!--22-->
195     <dependency>
196       <groupId>commons-fileupload</groupId>
197       <artifactId>commons-fileupload</artifactId>
198       <version>1.3.3</version>
199     </dependency>
200 
201     <!--23 下载ajax封装数据json格式交互的jar-->
202     <dependency>
203       <groupId>com.fasterxml.jackson.core</groupId>
204       <artifactId>jackson-databind</artifactId>
205       <version>2.9.6</version>
206     </dependency>
207 
208     <dependency>
209       <groupId>com.fasterxml.jackson.core</groupId>
210       <artifactId>jackson-core</artifactId>
211       <version>2.9.6</version>
212     </dependency>
213 
214     <dependency>
215       <groupId>com.fasterxml.jackson.core</groupId>
216       <artifactId>jackson-annotations</artifactId>
217       <version>2.9.6</version>
218     </dependency>
219 
220     <!--使用4的版本否则springmvc的xml-->
221     <dependency>
222       <groupId>com.github.pagehelper</groupId>
223       <artifactId>pagehelper</artifactId>
224       <version>4.1.6</version>
225     </dependency>
226   </dependencies>
227 
228 </project>
pom.xml

3、在项目的webapp目录下的WEB-INF下构建springmvc的xml文件,即springmvc-servlet.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:aop="http://www.springframework.org/schema/aop"
 5        xmlns:context="http://www.springframework.org/schema/context"
 6        xmlns:tx="http://www.springframework.org/schema/tx"
 7        xmlns:mvc="http://www.springframework.org/schema/mvc"
 8        xsi:schemaLocation="http://www.springframework.org/schema/beans
 9        http://www.springframework.org/schema/beans/spring-beans.xsd
10        http://www.springframework.org/schema/aop
11        http://www.springframework.org/schema/aop/spring-aop.xsd
12        http://www.springframework.org/schema/context
13        http://www.springframework.org/schema/context/spring-context.xsd
14        http://www.springframework.org/schema/tx
15        http://www.springframework.org/schema/tx/spring-tx.xsd
16        http://www.springframework.org/schema/mvc
17        http://www.springframework.org/schema/mvc/spring-mvc.xsd
18 ">
19    <!--1.mvc 注解驱动  -->
20     <mvc:annotation-driven/>
21    <!--2.全局扫描包-->
22     <context:component-scan base-package="com"/>
23    <!--3.驱动管理数据源 -->
24     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
25          <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
26          <property name="url" value="jdbc:mysql://localhost:3306/ar"/>
27          <property name="username" value="root"/>
28          <property name="password" value="123456"/>
29     </bean>
30     <!--4.数据源事务管理-->
31     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
32          <property name="dataSource" ref="dataSource"/>
33     </bean>
34     <!--5.事务注解驱动-->
35     <tx:annotation-driven transaction-manager="transactionManager"/>
36     <!--6.sqlsessionfactorybean-->
37     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
38           <property name="dataSource" ref="dataSource"/>
39           <!--映射xml文件需要类全路径别名的 配置,将某个包下的所有类全路径配置别名,别名默认是类名-->
40           <property name="typeAliasesPackage" value="com.pojo"/>
41            <!--引用映射xml文件-->
42           <property name="mapperLocations" value="classpath:mapper/*.xml"/>
43     </bean>
44     <!--7.映射扫描参数-->
45     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
46         <property name="basePackage" value="com.mapper"/>
47     </bean>
48 
49 </beans>
springmvc-servlet.xml

4、在项目的webapp目录下的WEB-INF下构建web的xml文件,即web.xml

 1 <!DOCTYPE web-app PUBLIC
 2  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 3  "http://java.sun.com/dtd/web-app_2_3.dtd" >
 4 
 5 <web-app>
 6   <!--springmvc的过滤器,主要过滤乱码-->
 7   <filter>
 8     <filter-name>character</filter-name>
 9     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
10     <init-param>
11       <param-name>encoding</param-name>
12       <param-value>UTF-8</param-value>
13     </init-param>
14   </filter>
15   <filter-mapping>
16     <filter-name>character</filter-name>
17     <url-pattern>/*</url-pattern>
18   </filter-mapping>
19 
20   <!--springmvc 核心拦截器-->
21    <servlet>
22      <servlet-name>springmvc</servlet-name>
23      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
24    </servlet>
25   <servlet-mapping>
26     <servlet-name>springmvc</servlet-name>
27     <url-pattern>*.do</url-pattern>
28   </servlet-mapping>
29   
30   <welcome-file-list>
31     <welcome-file>show.do</welcome-file>
32   </welcome-file-list>
33 </web-app>
web.xml

5、在java目录下的com.pojo包下构建Emp.java和Dept.java文件

 1 package com.pojo;
 2 import org.springframework.stereotype.Component;
 3 
 4 import java.io.Serializable;
 5 import java.util.List;
 6 /**
 7  * 一方引用多方list集合
 8  */
 9 @Component
10 public class Dept implements Serializable {
11   private Integer deptno   ;
12   private String  dname    ;
13   private String  loc          ;
14 
15   public Dept() {
16   }
17 
18   public Dept(Integer deptno, String dname, String loc) {
19     this.deptno = deptno;
20     this.dname = dname;
21     this.loc = loc;
22   }
23 
24   public Integer getDeptno() {
25     return deptno;
26   }
27 
28   public void setDeptno(Integer deptno) {
29     this.deptno = deptno;
30   }
31 
32 
33   public String getDname() {
34     return dname;
35   }
36 
37   public void setDname(String dname) {
38     this.dname = dname;
39   }
40 
41 
42   public String getLoc() {
43     return loc;
44   }
45 
46   public void setLoc(String loc) {
47     this.loc = loc;
48   }
49 
50   @Override
51   public String toString() {
52     return "Dept{" +
53             "deptno=" + deptno +
54             ", dname="" + dname + """ +
55             ", loc="" + loc + """ +
56             "}";
57   }
58 }
Dept.java
  1 package com.pojo;
  2 
  3 import org.springframework.stereotype.Component;
  4 
  5 import java.io.Serializable;
  6 
  7 /**
  8  * 多方引用一方对象
  9  */
 10 @Component
 11 public class Emp implements Serializable{
 12   private Integer empno             ;
 13   private String  ename           ;
 14   private String  job         ;
 15   private Integer mgr           ;
 16   private String  hiredate           ;
 17   private Double  sal         ;
 18   private Double  comm               ;
 19   private Dept dept;
 20 
 21   public Emp() {
 22   }
 23 
 24   public Emp(Integer empno, String ename, String job, Integer mgr, String hiredate, Double sal, Double comm, Dept dept) {
 25     this.empno = empno;
 26     this.ename = ename;
 27     this.job = job;
 28     this.mgr = mgr;
 29     this.hiredate = hiredate;
 30     this.sal = sal;
 31     this.comm = comm;
 32     this.dept = dept;
 33   }
 34 
 35   public Integer getEmpno() {
 36     return empno;
 37   }
 38 
 39   public void setEmpno(Integer empno) {
 40     this.empno = empno;
 41   }
 42 
 43 
 44   public String getEname() {
 45     return ename;
 46   }
 47 
 48   public void setEname(String ename) {
 49     this.ename = ename;
 50   }
 51 
 52 
 53   public String getJob() {
 54     return job;
 55   }
 56 
 57   public void setJob(String job) {
 58     this.job = job;
 59   }
 60 
 61 
 62   public Integer getMgr() {
 63     return mgr;
 64   }
 65 
 66   public void setMgr(Integer mgr) {
 67     this.mgr = mgr;
 68   }
 69 
 70 
 71   public String getHiredate() {
 72     return hiredate;
 73   }
 74 
 75   public void setHiredate(String hiredate) {
 76     this.hiredate = hiredate;
 77   }
 78 
 79 
 80   public Double getSal() {
 81     return sal;
 82   }
 83 
 84   public void setSal(Double sal) {
 85     this.sal = sal;
 86   }
 87 
 88 
 89   public Double getComm() {
 90     return comm;
 91   }
 92 
 93   public void setComm(Double comm) {
 94     this.comm = comm;
 95   }
 96 
 97   public Dept getDept() {
 98     return dept;
 99   }
100 
101   public void setDept(Dept dept) {
102     this.dept = dept;
103   }
104 
105   @Override
106   public String toString() {
107     return "Emp{" +
108             "empno=" + empno +
109             ", ename="" + ename + """ +
110             ", job="" + job + """ +
111             ", mgr=" + mgr +
112             ", hiredate="" + hiredate + """ +
113             ", sal=" + sal +
114             ", comm=" + comm +
115             ", dept=" + dept +
116             "}";
117   }
118 }
Emp.java

6、在java目录下的com.mapper包下构建映射接口EmpMapper.java和DeptMapper.java文件

1 package com.mapper;
2 import com.pojo.Dept;
3 import org.springframework.stereotype.Repository;
4 
5 import java.util.List;
6 @Repository
7 public interface DeptMapper {
8     List<Dept> selectAllDept();
9 }
DeptMapper.java
 1 package com.mapper;
 2 import com.pojo.Emp;
 3 import org.springframework.stereotype.Repository;
 4 
 5 import java.util.List;
 6 @Repository
 7 public interface EmpMapper {
 8     List<Emp> selectEmp(Emp emp);
 9     int insertEmp(Emp emp);
10     int updateEmp(Emp emp);
11     int deleteEmp(Emp emp);
12 }
EmpMapper.java

7、在java目录下的com.service包下构建2个业务层接口EmpService.java 和DeptService.java文件,2个业务层接口实现类EmpServiceImpl.java 和DeptServiceImpl.java文件

1 package com.service;
2 
3 import com.pojo.Dept;
4 
5 import java.util.List;
6 
7 public interface DeptService {
8     List<Dept> downOption();
9 }
DeptService.java
 1 package com.service;
 2 
 3 import com.pojo.Emp;
 4 
 5 import java.util.List;
 6 
 7 public interface EmpService {
 8     List<Emp> show(Emp emp);
 9     int add(Emp emp);
10     int edit(Emp emp);
11     int del(Emp emp);
12 }
EmpService.java
 1 package com.service;
 2 
 3 import com.mapper.DeptMapper;
 4 import com.pojo.Dept;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Service;
 7 
 8 import java.util.List;
 9 @Service
10 public class DeptServiceImpl implements DeptService{
11     @Autowired
12     private DeptMapper deptMapper;
13 
14 
15     @Override
16     public List<Dept> downOption() {
17         return deptMapper.selectAllDept();
18     }
19 }
DeptServiceImpl.java
 1 package com.service;
 2 
 3 import com.mapper.EmpMapper;
 4 import com.pojo.Emp;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Service;
 7 
 8 import javax.annotation.Resource;
 9 import java.util.List;
10 /*
11 @Service的功能等同于代理对象在spring的xml文件中动态添加bean节点,
12 如果不指定名称,则底层代理在构建bean节点的时候id是类的第一个首字母小写
13 <bean id="empServiceImpl" class="com.service.EmpServiceImpl"/>
14 @Service(value = "empse")的功能等同于代理对象在spring的xml文件中动态添加id值为empse的bean节点
15 <bean id="empse" class="com.service.EmpServiceImpl"/>
16 */
17 @Service
18 public class EmpServiceImpl implements EmpService {
19     /*
20     @Autowired是spring的资源包下注解,按照对象的类型进行自动注入,
21     和对象名称无关,只要类型是匹配的,代理就会在你需要的时候给你注入对象值
22     @Resource是javax包下的注解,按照对象属性名进行注入,
23     和对象名称关系密切,如果对象名称不匹配,则不能完成注入,会报错
24     总结:相比而言,使用@Resource的出错记录更大,因此我们常规选择使用@Autowired
25      */
26     @Autowired
27     private EmpMapper empMapper;
28 
29     @Override
30     public List<Emp> show(Emp emp) {
31         return empMapper.selectEmp(emp);
32     }
33 
34     @Override
35     public int add(Emp emp) {
36         return empMapper.insertEmp(emp);
37     }
38 
39     @Override
40     public int edit(Emp emp) {
41         return empMapper.updateEmp(emp);
42     }
43 
44     @Override
45     public int del(Emp emp) {
46         return empMapper.deleteEmp(emp);
47     }
48 }
EmpServiceImpl.java

8、在java目录下的com.controller包下构建1个核心控制层类CenterController.java

 1 package com.controller;
 2 
 3 import com.pojo.Dept;
 4 import com.pojo.Emp;
 5 import com.service.DeptService;
 6 import com.service.EmpService;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.stereotype.Controller;
 9 import org.springframework.ui.Model;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import javax.servlet.http.HttpSession;
14 import java.util.List;
15 @Controller
16 public class CenterController {
17     @Autowired
18     private DeptService deptService;
19 
20     @Autowired
21     private EmpService empService;
22 
23     @RequestMapping("/show.do")
24     public String showData(HttpSession session, Model model){
25         List<Dept> deptlist=deptService.downOption();
26         session.setAttribute("deptlist",deptlist);
27 
28          List<Emp> emplist=empService.show(new Emp());
29 //        功能等同于request.setAttribute(key,value)
30         model.addAttribute("emplist",emplist);
31 
32         //默认跳转使用转发
33         return "main.jsp";
34     }
35 
36 
37     @RequestMapping("/option.do")
38     public String showOption(Emp emp,Model model){
39         List<Emp> emplist=empService.show(emp);
40 
41 //        功能等同于request.setAttribute(key,value)
42         model.addAttribute("emplist",emplist);
43         model.addAttribute("deptno",emp.getDept().getDeptno());
44 
45         //默认跳转使用转发
46         return "main.jsp";
47     }
48 
49     @RequestMapping("/info.do")
50     public String showInfo(Emp emp,Model model){
51         //根据主键编号查询只有一条数据
52         Emp emp2=empService.show(emp).get(0);
53 
54 //        功能等同于request.setAttribute(key,value)
55         model.addAttribute("emp2",emp2);
56 
57         //默认跳转使用转发
58         return "edit.jsp";
59     }
60     @RequestMapping("/edit.do")
61     public String edit(Emp emp){
62         //根据主键编号查询只有一条数据
63         System.out.println(empService.edit(emp)>0?"edit success":"edit fail");;
64         //使用重定向跳转
65         return "redirect:/show.do";
66     }
67 
68     @RequestMapping("/add.do")
69     public String add(Emp emp){
70         //根据主键编号查询只有一条数据
71         System.out.println(empService.add(emp)>0?"add success":"add fail");;
72         //使用重定向跳转
73         return "redirect:/show.do";
74     }
75 
76     @RequestMapping("/del.do")
77     public String del(Emp emp){
78         //根据主键编号查询只有一条数据
79         System.out.println(empService.del(emp)>0?"del success":"del fail");;
80         //使用重定向跳转
81         return "redirect:/show.do";
82     }
83 }
CenterController.java

9、在resouces目录下构建1个系统日志记录文件log4j.properties

 1 log4j.rootLogger=DEBUG, Console  
 2 #Console  
 3 log4j.appender.Console=org.apache.log4j.ConsoleAppender  
 4 log4j.appender.Console.layout=org.apache.log4j.PatternLayout  
 5 log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  
 6 
 7 log4j.logger.org.apache=INFO  
 8 log4j.logger.java.sql.ResultSet=INFO  
 9 log4j.logger.java.sql.Connection=DEBUG  
10 log4j.logger.java.sql.Statement=DEBUG  
11 log4j.logger.java.sql.PreparedStatement=DEBUG   
log4j.properties

10、在resouces目录下的mapper目录下构建2个映射xml文件DeptMapper.xml和EmpMapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <!--配置规则:-->
 4 <!--有代理的namespace值必须是映射接口全路径,sql节点的id值必须是映射接口中的方法名-->
 5 <!--无代理的namespace值和sql节点的id值是任意的,但一般情况下和和有代理的原则一样-->
 6 <mapper namespace="com.mapper.DeptMapper">
 7      <select id="selectAllDept" resultType="Dept">
 8           select * from dept
 9      </select>
10 </mapper>
DeptMapper.xml
  1 <?xml version="1.0" encoding="UTF-8" ?>
  2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3 <mapper namespace="com.mapper.EmpMapper">
  4    <!-- 案例:select * from emp where empno=#{empno} or ename=#{ename} and job=#{job}
  5     如果select节点中是以上sql语句,parameterType是Emp类型,则此情况可以使用where标签,
  6     where标签的作用是如果if条件不满足则执行,如果满足if条件将会忽略where关键字后的
  7     第一个or或and
  8     select * from emp
  9     <where>
 10         <if test="empno!=null">
 11             empno=#{empno}
 12         </if>
 13         <if test="ename!=null">
 14            or ename=#{ename}
 15         </if>
 16         <if test="job!=null">
 17            and job=#{job}
 18         </if>
 19     </where>
 20     -->
 21     <!--if或when的test条件中的属性判断,必须从参数对象的第一层属性判断起,-->
 22     <!--如果Emp类中有empno属性,有dept对象属性,则要判断empno值和dept中deptno的值,-->
 23     <!--则写法是empno!=null,dept!=null && dept.deptno!=null-->
 24     <select id="selectEmp" resultMap="empmap" parameterType="Emp">
 25          select d.dname,d.loc,e.* from emp e,dept d where e.deptno=d.deptno
 26          <if test="empno!=null">
 27              and e.empno=#{empno}
 28          </if>
 29          <if test="ename!=null">
 30              and e.ename=#{ename}
 31          </if>
 32          <if test="job!=null">
 33              and e.job=#{job}
 34          </if>
 35          <if test="dept!=null and dept.deptno!=null">
 36              and e.deptno=#{dept.deptno}
 37          </if>
 38     </select>
 39 
 40     <resultMap id="empmap" type="Emp">
 41         <!--因为当前多方配置,因此在resultMap中先配置多方的主键和普通列的映射-->
 42         <id column="EMPNO" property="empno"/>
 43         <result column="ENAME" property="ename"/>
 44         <result column="JOB " property="job"/>
 45         <result column="MGR" property="mgr"/>
 46         <result column="HIREDATE" property="hiredate"/>
 47         <result column="SAL" property="sal"/>
 48         <result column="COMM" property="comm"/>
 49 
 50         <!--因为在多方引用了一方的对象,因此在引用一方对象属性的地方配置association节点-->
 51         <!--association节点的property属性对应的多方引用一方的对象属性名,-->
 52         <!--javaType是多方引用一方的类类型即配置类的全路径-->
 53         <!--column是多方关联一方的外键列的列名-->
 54         <association property="dept" javaType="Dept" column="DEPTNO">
 55             <!--由于多方引用的了一方对象,因此在association对象节点下配置一方的主键和普通字段-->
 56             <id column="DEPTNO" property="deptno"/>
 57             <result column="DNAME" property="dname"/>
 58             <result column="LOC" property="loc"/>
 59         </association>
 60     </resultMap>
 61 
 62     <insert id="insertEmp" parameterType="Emp">
 63          INSERT  INTO emp(empno, ename, job, mgr, hiredate, sal, comm, deptno) VALUES
 64          (#{empno},#{ename},#{job},#{mgr},#{hiredate},#{sal},#{comm},#{dept.deptno})
 65     </insert>
 66 
 67     <!--set标签的结束标签要在where条件之前-->
 68     <update id="updateEmp" parameterType="Emp">
 69         UPDATE emp
 70         <set>
 71             <if test="ename!=null">
 72                 ename=#{ename} ,
 73             </if>
 74             <if test="job!=null">
 75                 job=#{job} ,
 76             </if>
 77             <if test="mgr!=null">
 78                    mgr=#{mgr} ,
 79             </if>
 80             <if test="hiredate!=null">
 81                 hiredate=#{hiredate} ,
 82             </if>
 83             <if test="sal!=null">
 84                  sal=#{sal},
 85             </if>
 86             <if test="comm!=null">
 87                comm=#{comm},
 88             </if>
 89             <if test="dept!=null and dept.deptno!=null">
 90                deptno=#{dept.deptno}  ,
 91             </if>
 92         </set>
 93         <include refid="wherecondition"/>
 94     </update>
 95 
 96     <delete id="deleteEmp" parameterType="Emp">
 97         delete from emp
 98         <include refid="wherecondition"/>
 99     </delete>
100 
101      <!--定义公共的sql片段-->
102    <sql id="wherecondition">
103        <where>
104            <if test="empno!=null">
105                empno=#{empno}
106            </if>
107        </where>
108    </sql>
109 
110 </mapper>
EmpMapper.xml

11、在项目的webapp目录下构建main.jsp

 1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 2 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 3 <%@ page isELIgnored="false" %>
 4 <html>
 5 <head>
 6     <title>首页</title>
 7 </head>
 8 <body>
 9    <a href="add.jsp">添加</a>
10     <p>
11       <form action="option.do" method="post">
12          <span>部门:</span>
13         <select name="dept.deptno">
14             <option value="-1">--请选择--</option>
15             <c:forEach var="i" items="${deptlist}">
16                   <c:choose>
17                       <c:when test="${deptno eq i.deptno}">
18                          <option value="${i.deptno}" selected="selected">${i.dname}</option>
19                       </c:when>
20                       <c:otherwise>
21                          <option value="${i.deptno}">${i.dname}</option>
22                       </c:otherwise>
23                   </c:choose>
24             </c:forEach>
25         </select>
26         <input type="submit" value="查询">
27       </form>
28     </p>
29     <table>
30         <tr>
31             <th>员工编号</th>
32             <th>员工姓名</th>
33             <th>员工薪资</th>
34             <th>部门名称</th>
35             <th>操作</th>
36         </tr>
37         <c:forEach var="i" items="${emplist}">
38              <tr>
39                  <td>${i.empno}</td>
40                  <td>${i.ename}</td>
41                  <td>${i.sal}</td>
42                  <td>${i.dept.dname}</td>
43                  <td>
44                      <a href="info.do?empno=${i.empno}">修改</a>
45                      |
46                      <a href="del.do?empno=${i.empno}">删除</a>
47                  </td>
48              </tr>
49         </c:forEach>
50     </table>
51 </body>
52 </html>
main.jsp

12、在项目的webapp目录下构建edit.jsp

 1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 2 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 3 <%@ page isELIgnored="false" %>
 4 <html>
 5 <head>
 6     <title>编辑信息</title>
 7 </head>
 8 <body>
 9    <fieldset>
10        <legend>编辑员工信息</legend>
11        <form action="edit.do?empno=${emp2.empno}" method="post">
12            <table>
13                <tr>
14                    <th>部门名称:</th>
15                    <td>
16                        <select name="dept.deptno">
17                            <option value="-1">--请选择--</option>
18                            <c:forEach var="i" items="${deptlist}">
19                                <c:choose>
20                                    <c:when test="${emp2.dept.deptno eq i.deptno}">
21                                        <option value="${i.deptno}" selected="selected">${i.dname}</option>
22                                    </c:when>
23                                    <c:otherwise>
24                                        <option value="${i.deptno}">${i.dname}</option>
25                                    </c:otherwise>
26                                </c:choose>
27                            </c:forEach>
28                        </select>
29                    </td>
30                </tr>
31                <tr>
32                    <th>员工姓名:</th>
33                    <td><input type="text" name="ename" value="${emp2.ename}"/></td>
34                </tr>
35                <tr>
36                    <th>员工薪资:</th>
37                    <td><input type="text" name="sal" value="${emp2.sal}"/></td>
38                </tr>
39                <tr>
40                    <td colspan="2" align="center">
41                        <input type="submit" value="提交"/>
42                        <input type="reset" value="重置"/>
43                    </td>
44                </tr>
45            </table>
46        </form>
47    </fieldset>
48 
49 </body>
50 </html>
edit.jsp

13、在项目的webapp目录下构建add.jsp

 1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 2 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 3 <%@ page isELIgnored="false" %>
 4 <html>
 5 <head>
 6     <title>添加信息</title>
 7 </head>
 8 <body>
 9    <fieldset>
10        <legend>添加员工信息</legend>
11        <form action="add.do" method="post">
12            <table>
13                <tr>
14                    <th>部门名称:</th>
15                    <td>
16                        <select name="dept.deptno">
17                            <option value="-1">--请选择--</option>
18                            <c:forEach var="i" items="${deptlist}">
19                                <option value="${i.deptno}">${i.dname}</option>
20                            </c:forEach>
21                        </select>
22                    </td>
23                </tr>
24                <tr>
25                    <th>员工编号:</th>
26                    <td><input type="text" name="empno"/></td>
27                </tr>
28                <tr>
29                    <th>员工姓名:</th>
30                    <td><input type="text" name="ename" /></td>
31                </tr>
32                <tr>
33                    <th>员工薪资:</th>
34                    <td><input type="text" name="sal" /></td>
35                </tr>
36                <tr>
37                    <td colspan="2" align="center">
38                        <input type="submit" value="提交"/>
39                        <input type="reset" value="重置"/>
40                    </td>
41                </tr>
42            </table>
43        </form>
44    </fieldset>
45 </body>
46 </html>
add.jsp

14、部署启动项目查看效果

 

 

 

 

 

 

 

 

 

  此文章为原创,转载请注明出处!需要本案例源码,理论讲解视频,代码操作视频的,请私信联系作者!

原文地址:https://www.cnblogs.com/holly8/archive/2022/08/19/16602450.html