有些东西,真的得自己记录一下。就算有太多的资料,但是自己实现起来还不是那么顺利。就像这个SSM框架整合一样(SSH配置起来一样坑不少,最恶心的还是找jar包。光找jar包上SSM就比SSH好不少,别的说实话我也不清楚,毕竟不是干JavaEE的)。弄这个主要还是想自己练习写App,同时还能练习写接口练练Sql语句。因为写练习也不能总写Servlet + JDBC,总这么写也没啥意思。所以还得了解了解框架,这样以后吹牛逼还能掺和两嘴装装B。
我电脑的环境配置是JDK1.8,Tomcat8.5,Eclipse4.7.0。因为我就是练习,所以基本用的都是比较新的。因为用Maven比较方便,这里就直接用Maven项目了,这里贴一下pom.xml里的配置。(创建Maven项目没啥东西,这里就不贴图了)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>LyangroupId>
<artifactId>SMartifactId>
<version>0.0.1-SNAPSHOTversion>
<packaging>warpackaging>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<spring.version>4.3.10.RELEASEspring.version>
<slf4j.version>1.7.22slf4j.version>
<jackJson.version>2.8.9jackJson.version>
properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.6.0version>
<configuration>
<source>1.8source>
<target>1.8target>
<encoding>${project.build.sourceEncoding}encoding>
<compilerArguments>
<verbose />
<bootclasspath>${java.home}/lib/rt.jar;${java.home}/lib/jce.jarbootclasspath>
compilerArguments>
configuration>
plugin>
plugins>
build>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.43version>
dependency>
<dependency>
<groupId>cglibgroupId>
<artifactId>cglibartifactId>
<version>3.2.4version>
dependency>
<dependency>
<groupId>commons-logginggroupId>
<artifactId>commons-loggingartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-coreartifactId>
<version>2.3version>
dependency>
<dependency>
<groupId>ognlgroupId>
<artifactId>ognlartifactId>
<version>3.1.12version>
dependency>
<dependency>
<groupId>org.javassistgroupId>
<artifactId>javassistartifactId>
<version>3.21.0-GAversion>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>${jackJson.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>${jackJson.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>${jackJson.version}version>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-dbcp2artifactId>
<version>2.1.1version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
dependencies>
project>
我这些依赖和配置,用来做练习写接口绝对够了。Mysql数据库驱动、Dbcp连接池、JSON解析啥的都有。要是别的想用的Jar,那就直接用Maven Repository搜就行了
这里先测试Mybatis好不好使,然后再整合Spring + Mybatis。这里先创建两个配置文件如下图所示:
jdbc.properties文件配置如下,也没啥玩意,就是设置驱动,数据库连接,用户名和用户密码。
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\:///S_M?useUnicode\=true&characterEncoding\=utf8&useSSL\=false
username=root
password=root
log4j.properties文件配置如下,这个我感觉我没用到(这个我直接拿别人的用了,主要是我怕不配置会报错!)。配置如下:
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
在测试之前,先创建数据库并创建一张表。库名简单点就叫S_M了,然后创建一张person表放上三个字段,id、name、age。(反反正就是用来练习,越简单越好)
创建Mybatis配置文件,文件名为mybatis_config.xml,文件放置位置如下图所示:
配置内容如下:
<configuration>
<properties resource="jdbc.properties" />
<typeAliases>
<package name="com.mine.test.bean"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
dataSource>
environment>
environments>
<mappers>
<package name="com.mine.test.mapper"/>
mappers>
configuration>
接下来先创建POJO类,也就是Person类。这个简单,就是一个类有三个属性,分别是id、name和age。
package com.mine.test.bean;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Person implements Serializable{
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
有了Person类之后,就创建映射文件,这里就创建一个方法用来增加数据用来测试:
【PersonMapper.java】配置如下:
package com.mine.test.mapper;
import com.mine.test.bean.Person;
public interface PersonMapper {
public void addPerson(Person person);
}
【PersonMapper.xml】配置如下:
<mapper namespace="com.mine.test.mapper.PersonMapper">
<insert id="addPerson" parameterType="person" useGeneratedKeys="true"
keyProperty="id">
insert into
person(name,age)
values(#{name},#{age})
insert>
mapper>
【DataTest.java】用来测试增加方法是否可用。测试代码如下:
package com.mine.test;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mine.test.bean.Person;
import com.mine.test.mapper.PersonMapper;
public class DataTest {
private SqlSession sqlSession;
@Before
public void before() throws IOException {
String resource = "mybatis_config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession();
}
/**
* 测试查询一条记录
*/
@Test
public void selectOne() {
PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
Person person = new Person();
person.setName("西北风");
person.setAge(28);
personMapper.addPerson(person);
System.out.println("新增人员的ID->" + person.getId());
sqlSession.commit();
}
@After
public void after() {
sqlSession.close();
}
}
运行结果成功,运行结果如下图。
这里在查询一下person表进行验证,查看数据是否插入到表中。查询结果说明Mybatis可用没有问题。
之前验证了Mybatis可用,在这步将整合Spring和Mybatis。然后再测试一下整合后是否可用。这里先在资源文件创建Spring的配置文件。
这里我创建了两个xml文件,一个是主配置文件applicationContext.xml,另一个jdbc.xml用来配置数据库连接池和事务管理(这里是怕配置太多显得乱,所以将配置数据库方面的配置拿了出来,放在了jdbc.xml中)。
jdbc.xml中的配置如下:
<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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.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.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-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:property-placeholder location="classpath:jdbc.properties"
system-properties-mode="NEVER" />
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<property name="maxTotal" value="10" />
<property name="maxIdle" value="5" />
bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis_config.xml" />
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mine.test.mapper" />
bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
bean>
<tx:annotation-driven transaction-manager="transactionManager" />
beans>
在applicationContext.xml中引入jdbc.xml配置文件:
<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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<import resource="classpath:jdbc.xml" />
beans>
接下来修改一下mybatis_config.xml配置文件,应为将数据库连接交给了Spring去处理,所以将mybatis_config.xml改造下面的效果,代码如下:
<configuration>
<typeAliases>
<package name="com.mine.test.bean"/>
typeAliases>
<mappers>
<package name="com.mine.test.mapper"/>
mappers>
configuration>
到这里Spring+整合Mybatis的配置部分就完成了,接下来测试一下。这里先在PersonMapper.xml增加一个更新数据的语句。代码如下:
<mapper namespace="com.mine.test.mapper.PersonMapper">
<insert id="addPerson" parameterType="person" useGeneratedKeys="true"
keyProperty="id">
insert into
person(name,age)
values(#{name},#{age})
insert>
<update id="updatePersonMsg" parameterType="person">
update person set
name=#{name},age=#{age} where id = #{id}
update>
mapper>
在PersonMapper接口中增加updatePersonMsg()方法(※方法名称要与映射文件中的id相同,update和delete操作默认是有返回值的),代码如下:
package com.mine.test.mapper;
import com.mine.test.bean.Person;
public interface PersonMapper {
void addPerson(Person person);//增加数据
int updatePersonMsg(Person person);//更新数据
}
接下来修改一下DataTest.java测试类,这里将使用Spring结合Junit来进行测试。这样就不需要我们手写读取配置的代码了,测试代码如下:
package com.mine.test;
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.mine.test.bean.Person;
import com.mine.test.mapper.PersonMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class DataTest {
@Autowired
PersonMapper personMapper;
@Test
public void upDateMsg() {
Person person = new Person();
person.setName("东南风");
person.setAge(30);
int result = personMapper.updatePersonMsg(person);
System.out.println("影响行数->" + result);
}
}
测试打印的结果如下图所示:
查看数据库中数据的是否发生变化:
首先先创建一个名为SpringMvc.xml配置文件,创建位置如下图所示:
配置如下,这里我只是练习写接口,所以配置就简单很多,配置如下:
<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"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<context:component-scan base-package="com.mine.test.controller" />
<mvc:annotation-driven />
beans>
接下来配置web.xml文件,配置一下请求拦击方式和字符集,配置如下:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>SMdisplay-name>
<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>springMvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springMvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springMvcservlet-name>
<url-pattern>*.dourl-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>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
web-app>
接下来就是测试功能好不好用,这里先创建几个文件用于测试,类似于下图:
这里先修改一下PersonMapper映射文件,增加一个查询方法:
PersonMapper.java如下:
package com.mine.test.mapper;
import com.mine.test.bean.Person;
public interface PersonMapper {
void addPerson(Person person);//增加数据
int updatePersonMsg(Person person);//更新数据
Person selectOne(Integer id);//查询
}
PersonMapper.xml如下:
<mapper namespace="com.mine.test.mapper.PersonMapper">
<insert id="addPerson" parameterType="person" useGeneratedKeys="true"
keyProperty="id">
insert into
person(name,age)
values(#{name},#{age})
insert>
<update id="updatePersonMsg" parameterType="person">
update person set
name=#{name},age=#{age} where id = #{id}
update>
<select id="selectOne" parameterType="int" resultType="person">
select * from person where
id = #{id}
select>
mapper>
创建Service接口,设置一个查询方法,代码如下:
package com.mine.test.service;
import com.mine.test.bean.Person;
public interface TestService {
Person selectOne(Integer id);
}
创建Service接口的实现类,设置一个查询方法,代码如下:
package com.mine.test.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mine.test.bean.Person;
import com.mine.test.mapper.PersonMapper;
import com.mine.test.service.TestService;
@Service
public class TestServiceImpl implements TestService{
@Autowired
PersonMapper personMapper;
@Override
public Person selectOne(Integer id) {
return personMapper.selectOne(id);
}
}
在applicationContext.xml加入扫描Service的设置,代码如下:
<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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<import resource="classpath:jdbc.xml" />
<context:component-scan base-package="com.mine.test.service.impl" />
beans>
创建Controller,用来接收请求。代码如下:
package com.mine.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mine.test.bean.Person;
import com.mine.test.service.TestService;
@Controller
public class TestController {
@Autowired
TestService service;
@RequestMapping(value = "/test")
@ResponseBody
public Person getPerson(@RequestParam Integer id) {
return service.selectOne(id);
}
}
在index.jsp中增加一个求情表单,用来发起查询请求。代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
<form action="test.do" method="post">
<label>查询IDlabel>
<br>
<input type="submit" name="提交">
form>
body>
html>