本项目是使用spring+springmvc+mabatis框架实现的一个增删改查应用
整体框架如图:
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.7maven.compiler.source>
<maven.compiler.target>1.7maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>5.0.0version>
dependency>
<dependency>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-coreartifactId>
<version>1.3.5version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.8.8version>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-validatorartifactId>
<version>5.4.1.Finalversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.41version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.5version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.7.12version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-pluginartifactId>
<version>2.5version>
<executions>
<execution>
<id>copy-xmlsid>
<phase>process-sourcesphase>
<goals>
<goal>copy-resourcesgoal>
goals>
<configuration>
<outputDirectory>${basedir}/target/classesoutputDirectory>
<resources>
<resource>
<directory>${basedir}/src/main/javadirectory>
<includes>
<include>**/*.xmlinclude>
<include>**/*.propertiesinclude>
includes>
resource>
resources>
configuration>
execution>
executions>
plugin>
plugins>
build>
注意:打包时,maven并不会把resources
(注意拼写后面有s的)里的配置文件一起打包到classes类路径下的,所以我们需要添加插件打包时指定配置文件存放在哪里,参考Maven总结
添加spring等配置的时候,需要idea增加框架支持才能生成相关配置文件,如图:
若打开界面没有spring相关配置信息,则我们要先删除项目自带的spring,然后再回到这里重新添加,如图:
这样,IDEA会在增加相关配置文件以及web里添加一些spring 信息,如图:
<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">
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
<init-param>
<param-name>forceRequestEncodingparam-name>
<param-value>trueparam-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>HiddenHttpMethodFilterfilter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>HttpPutFormContentFilterfilter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilterfilter-class>
filter>
<filter-mapping>
<filter-name>HttpPutFormContentFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<context-param>
<param-name>log4jparam-name>
<param-value>classpath:log4j.propertiesparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListenerlistener-class>
listener>
web-app>
jdbc.jdbcUrl=jdbc:mysql://192.168.10.128:3306/ssm_crud
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root
1.类根目录下创建存放映射的目录以及mybatis配置文件,如图:
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
settings>
<typeAliases>
<package name="com.zy.crud.bean"/>
typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="reasonable" value="true"/>
plugin>
plugins>
configuration>
由于我们在eclipse里需要用到一些spring的命名空间的时候,可以通过界面勾选添加,这里IDEA不用那么麻烦,在编辑区,直接输入想要配置的标签,然后输入冒号(:),自动提示了可能需要配置的标签以及对应的命名空间。选择我们对应的标签,命名空间自动就导入了
<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/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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.zy">
<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.jdbcUrl}">property>
<property name="driverClass" value="${jdbc.driverClass}">property>
<property name="user" value="${jdbc.user}">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>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.zy.crud.dao">property>
bean>
<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>
<aop:config>
<aop:pointcut expression="execution(* com.zy.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="*"/>
<tx:method name="get*" read-only="true"/>
tx:attributes>
tx:advice>
beans>
servlet-name :随便取。Spring默认配置文件为"/WEB-INF/[servlet-name]-servlet.xml"。
<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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.zy" 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:default-servlet-handler>
<mvc:annotation-driven>mvc:annotation-driven>
beans>
emp 人员表
DROP TABLE IF EXISTS `tbl_emp`;
CREATE TABLE `tbl_emp` (
`emp_id` int(11) NOT NULL AUTO_INCREMENT,
`emp_name` varchar(255) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`d_id` int(11) DEFAULT NULL,
PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SET FOREIGN_KEY_CHECKS=1;
dept 部门表
DROP TABLE IF EXISTS `tbl_dept`;
CREATE TABLE `tbl_dept` (
`dept_id` int(11) NOT NULL AUTO_INCREMENT,
`dept_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SET FOREIGN_KEY_CHECKS=1;
官网
1.添加依赖
<dependency>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-coreartifactId>
<version>1.3.5version>
dependency>
2.项目添加逆向工程配置文件mbg.xml
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.10.128:3306/ssm_crud" userId="root"
password="root">
jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
javaTypeResolver>
<javaModelGenerator targetPackage="com.zy.crud.bean"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
javaModelGenerator>
<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.zy.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>
1.创建测试类MBGTest
路径参考
public class MBGTest {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File(MBGTest.class.getResource("/").getPath()+"\\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);
System.out.println("创建实体类成功!!!");
}
}
2.修改其中mapper文件,支持查询人员的同时,顺带部门也查找出来
emp
<resultMap type="com.zy.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.zy.crud.bean.Department">
<id column="dept_id" property="deptId"/>
<result column="dept_name" property="deptName"/>
association>
resultMap>
<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>
<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>
1.添加Spring测试依赖
2.测试类MapperTest
/**
* 测试dao层的工作
*
* 以前需要在代码中这样写:
* 1、创建SpringIOC容器
* ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
* 2、从容器中获取mapper
* DepartmentMapper bean = ioc.getBean(DepartmentMapper.class);
*
* 自动注入:
*推荐Spring的项目就可以使用Spring的单元测试,可以自动注入我们需要的组件
*1、导入SpringTest模块
*2、@ContextConfiguration指定Spring配置文件的位置
*3、直接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(){
//1、插入几个部门
departmentMapper.insertSelective(new Department(null, "开发部"));
departmentMapper.insertSelective(new Department(null, "测试部"));
//2、生成员工数据,测试员工插入
employeeMapper.insertSelective(new Employee(null, "Jerry", "M", "[email protected]", 1));
//3、批量插入多个员工;批量,使用可以执行批量操作的sqlSession。
// for(){
// employeeMapper.insertSelective(new Employee(null, , "M", "[email protected]", 1));
// }
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
for(int i = 0;i<100;i++){
String uid = UUID.randomUUID().toString().substring(0,5)+i;
int seek = i % 2;
if(seek == 0){
mapper.insertSelective(new Employee(null,uid, "M", uid+"@demaxiya.com", (seek+1)));
}else{
mapper.insertSelective(new Employee(null,uid, "F", uid+"@kate.com", (seek+1)));
}
}
System.out.println("批量完成");
System.out.println("执行成功!");
}
}
1.applicationContext.xml增加配置,这个是mybatis给spring提供的批量功能
2.MapperTest代码自动注入批量session
3.测试,如“2.5.4 创建Spring单元测试”上面所示,执行即可。
官网
1.引入插件
pom.xml
mybatis-config.xml
1.web增加日志监听,并增加日志属性配置文件,如图:
2.级别配置成debug,方便sql打印,如图:
3.添加相关依赖包,如图:
@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());
}
}
}
总结:
1.ContextConfiguration若这个类加载不了web-info下面的配置文件,可以把配置文件放到resources目录里,这样可以引用类路径来访问
2.若web请求老是失败,可以检查一下请求是否到达后台,requestMap有没有被注释掉
3.若查询出来的数据不能封装,则需要看一下实体类中有参构造方法,那无参构造方法是否也在
源代码地址:基于SSM框架的CRUD源代码(后续提供)
注意:
1.本文只给出了框架相关配置信息以及基础代码,逻辑业务代码等并没有给出,全部源代码放到服务器上
源代码