一 新建一个web项目并引入相关jar包
二 建一个mybatisGenerator.xml 和一个test类用逆向工程生成代码
@Test
public void test() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mybatisGenerator.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);
}
<?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">
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybait?serverTimezone=UTC"
userId="root"
password="123456">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<javaModelGenerator targetPackage="com.atxiyou.ssm.beans" targetProject=".\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.atxiyou.ssm.mapper" targetProject=".\conf">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.atxiyou.ssm.mapper" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<table tableName="tbl_dept" domainObjectName="Department"></table>
<table tableName="tbl_employee" domainObjectName="Employee"></table>
</context>
</generatorConfiguration>
自动生成java bean,mapepr以及mapper.xml
在资源文件conf下创建applicationContext.xml,springmvc.xml,mybaits-config.xml文件并分别写入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:component-scan base-package="com.atxiyou.ssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="dataSourceTransactionManager" />
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean" >
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybaits-config.xml"></property>
<property name="mapperLocations" value="classpath:com/atxiyou/ssm/mapper/*.xml"></property>
<property name="typeAliasesPackage" value="com.atxiyou.ssm.beans"></property>
</bean>
<mybatis-spring:scan base-package="com.atxiyou.ssm.mapper"/>
</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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.atxiyou.ssm" 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>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
</beans>
<?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>
</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">
<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>
<!-- 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>
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<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.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>
</web-app>
显示所有的雇员信息
index.jsp中 写入 <a href="emps">List all emps</a>
Service:新建EmployeeService.java 类@Service
public class EmployeeService {
@Autowired
private EmployeeMapper employeeMapper; //自动注入Mapper类
public List<Employee> selectAllEmps() {
return employeeMapper.selectByExample(null); //从数据库中返回所有雇员信息
}
Controller: 新建EmployeeHandler.java 类
@Controller
public class EmployeeHandler {
@Autowired
private EmployeeService employeeService; //spring自动注入employeeService类
@RequestMapping(value="/emps",method=RequestMethod.GET) //使用REST技术
public String listEmps(Map<String,Object> maps) {
List<Employee> emps= employeeService.selectAllEmps(); //接收返回的雇员list对象
System.out.println(emps);
maps.put("emps", emps); //放入域对象中
return "list"; //请求转发到list.jsp页面中
}
编写前端的页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
<script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(function(){
$(".delete").click(function(){
var href=$(this).attr("href");
$("#deleteForm").attr("action",href).submit();
return false;
});
});
</script>
</head>
<body>
<form id="deleteForm" action="" method="post">
<input type="hidden" name="_method" value="DELETE"/>
</form>
<h1 align="center">员工信息表</h1>
<table align="center" border="1px" width="70%" cellspacing="0px" >
<tr>
<th>ID</th>
<th>LastName</th>
<th>Gender</th>
<th>Email</th>
<th>DeptName</th>
<th>Operation</th>
</tr>
<c:forEach items="${requestScope.emps}" var="emp">
<tr align="center">
<td>${emp.empid}</td>
<td>${emp.empname}</td>
<td>${emp.empsex }</td>
<td>${emp.empemail }</td>
<td>${emp.deptid }</td>
<td>
<a href="emp/${emp.empid }" class="delete" >Delete</a>
<a href="emp/${emp.empid }">Update</a>
</td>
</tr>
</c:forEach>
</table>
<a href="emp">ADD New Emp</a>
</body>
</html>
在数据库插入数据并在Tomcat中运行如下
这样就完成了SSM的整合。
员工的增删改代码如下EmployeeService.java
package com.atxiyou.ssm.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.atxiyou.ssm.beans.Employee;
import com.atxiyou.ssm.beans.EmployeeExample;
import com.atxiyou.ssm.mapper.EmployeeMapper;
@Service
public class EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
public List<Employee> selectAllEmps() {
return employeeMapper.selectByExample(null);
}
public void addEmp(Employee employee) {
employeeMapper.insertSelective(employee);
}
public void deleteEmpById(Integer empid) {
// TODO Auto-generated method stub
EmployeeExample employeeExample=new EmployeeExample();
employeeExample.createCriteria().andEmpidEqualTo(empid);
employeeMapper.deleteByExample(employeeExample);
}
public List<Employee> getEmpById(Integer empid) {
EmployeeExample employeeExample=new EmployeeExample();
employeeExample.createCriteria().andEmpidEqualTo(empid);
return employeeMapper.selectByExample(employeeExample);
}
public void updateEmp(Employee employee) {
EmployeeExample employeeExample=new EmployeeExample();
employeeExample.createCriteria().andEmpidEqualTo(employee.getEmpid());
employeeMapper.updateByExampleSelective(employee, employeeExample);
}
}
DepartmentService.java
package com.atxiyou.ssm.service;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.atxiyou.ssm.beans.Department;
import com.atxiyou.ssm.mapper.DepartmentMapper;
@Service
public class DepartmentService {
@Autowired
private DepartmentMapper departmentMapper;
public Collection<Department> selectAllDep() {
return departmentMapper.selectByExample(null);
}
}
EmployeeHandler.java
package com.atxiyou.ssm.handler;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.atxiyou.ssm.beans.Department;
import com.atxiyou.ssm.beans.Employee;
import com.atxiyou.ssm.service.DepartmentService;
import com.atxiyou.ssm.service.EmployeeService;
import com.sun.org.apache.bcel.internal.generic.NEW;
@Controller
public class EmployeeHandler {
@Autowired
private EmployeeService employeeService;
@Autowired
private DepartmentService departService;
@RequestMapping(value="/emps",method=RequestMethod.GET)
public String listEmps(Map<String,Object> maps) {
List<Employee> emps= employeeService.selectAllEmps();
System.out.println(emps);
maps.put("emps", emps);
return "list";
}
// @RequestMapping(value="/delete".method)
// public void deleteEmp() {
//
//
//
// }
@RequestMapping(value="/emp",method=RequestMethod.GET)
public String toAddPage(Map<String,Object> maps) {
Collection<Department> departments=departService.selectAllDep();
System.out.println("hello"+departments);
maps.put("departments", departments);
maps.put("employee", new Employee());
return "input";
}
@RequestMapping(value="/emp",method=RequestMethod.POST)
public String addEmp(Employee employee) {
System.out.println(employee);
employeeService.addEmp(employee);
return "redirect:/emps";
}
@RequestMapping(value="emp/{empid}",method=RequestMethod.DELETE)
public String deleteEmp(@PathVariable("empid")Integer empid) {
employeeService.deleteEmpById(empid);
return "redirect:/emps";
}
@RequestMapping(value="emp/{empid}",method=RequestMethod.GET)
public String toUpdatePage(@PathVariable("empid")Integer empid,Map<String,Object> maps) {
List<Employee> employee= employeeService.getEmpById(empid);
Employee employee2=employee.get(0);
System.out.println(employee2);
maps.put("employee",employee2);
Collection<Department> departments=departService.selectAllDep();
maps.put("departments", departments);
return "input";
}
@RequestMapping(value="/emp",method=RequestMethod.PUT)
public String UpdateEmp(Employee employee) {
employeeService.updateEmp(employee);
return "redirect:/emps";
}
}
相对应的input.jsp页面
<%@page import="java.util.Map"%>
<%@page import="java.util.HashMap"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
</head>
<body>
<form:form action="${pageContext.request.contextPath }/emp" method="post" modelAttribute="employee">
<c:if test="${employee.empid !=null }">
<form:hidden path="empid"/>
<input type="hidden" name="_method" value="PUT" />
</c:if>
empname:<form:input path="empname"/>
<br/>
<%
Map<String,String> genders=new HashMap<String,String>();
genders.put("male", "男");
genders.put("female", "女");
request.setAttribute("genders", genders);
%>
Gender:<form:radiobuttons path="empsex" items="${genders }"/>
<br/>
email:<form:input path="empemail"/>
department:<form:select path="deptid" items="${requestScope.departments}"
itemLabel="dname" itemValue="deptid">
</form:select>
<br/>
<c:if test="${employee.empid==null }" >
<input type="submit" value="Add"/>
</c:if>
<c:if test="${employee.empid!=null }" >
<input type="submit" value="Update"/>
</c:if>
</form:form>
</body>
</html>
github 地址:https://github.com/NUllBoss/SSM-.git