1.mybatis是比较新的半自动orm框架,效率也比较高,优点是sql语句的定制,管理与维护,包括优化,缺点是对开发人员的sql功底要求较高,如果比较复杂的查询,表与表之间的关系映射到对象与对象之间的关系时,mapper.xml中的配置会恶心死你;
2.demo中只涉及到一张user表,同样的,我将演示ssm对单表的操作;
3.与案例一相同,我还是会对dao进行抽离,使得抽离出的核心dao具有通用性,其他模块dao只需继承核心dao即可;
4.demo整体包结构
数据库
create database ssjdbc;//创建ssjdbc数据库 //创建user表 CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(32) DEFAULT NULL, `password` varchar(32) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; //插入数据3条 insert into user(username,password) values (1001,123),(1002,456),(1003,789);
5.各配置文件
(1)pom.xml
<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.0</modelVersion> <groupId>com.xiaog</groupId> <artifactId>testssm</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <!-- spring+springmvc顶级依赖包,包含spring-webmvc、spring-aop、spring-beans、 spring-context、spring-core、spring-jcl、spring-expression、spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.5.RELEASE</version> </dependency> <!-- spring-aop所依赖的静态代理 , 使用aop方式管理事务,在service方法执行前开启事务, 方法执行后提交事务,方法执行失败回滚事务--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.0</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.0</version> </dependency> <!-- 使用jdbcTemplate中的事务实现 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.5.RELEASE</version> </dependency> <!-- 数据库方面 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <!-- orm框架 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- Logback --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>org.logback-extensions</groupId> <artifactId>logback-ext-spring</artifactId> <version>0.1.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.12</version> </dependency> <!-- jsp需要 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency> </dependencies> <build> <defaultGoal>compile</defaultGoal> <plugins> <!-- maven插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.1</version> <configuration> <port>9999</port> <path>/testssm</path> <uriEncoding>UTF-8</uriEncoding> <finalName>testssm</finalName> <server>tomcat7</server> </configuration> </plugin> </plugins> </build> </project>
(2)spring-context.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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd" default-autowire="byName" default-lazy-init="true"> <description>Spring公共配置 </description> <!-- 1.扫描包: @Repository @Service @Autowired @Resource --> <context:component-scan base-package="com.xiaog.dao,com.xiaog.service" /> <!-- 2.加载配置文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 3.配置连接池 :druid连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接数量 --> <property name="initialSize" value="5" /> <!-- 最大连接数 --> <property name="maxActive" value="100" /> <!-- 最小连接数 --> <property name="minIdle" value="5" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="120000" /> <!-- 超过时间限制是否回收 --> <property name="removeAbandoned" value="true" /> <!-- 超过时间限制多长 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="120000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <!-- 用来检测连接是否有效的sql,要求是一个查询语句 --> <property name="validationQuery" value="SELECT 1" /> <!-- 申请连接的时候检测 --> <property name="testWhileIdle" value="true" /> <!-- 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 --> <property name="testOnBorrow" value="false" /> <!-- 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能 --> <property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <property name="defaultAutoCommit" value="false" /> <!-- 配置监控统计拦截的filters --> <property name="filters" value="stat"/> </bean> <!-- 4.spring集成mybatis --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis-config.xml" /> <property name="mapperLocations" value="classpath:mapper/*.xml" /> </bean> <!-- 5.配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 6.配置aop --> <!-- 配置通知: 定位方法 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" /> </tx:attributes> </tx:advice> <!-- 配置切面 --> <aop:config> <!-- 定位具体的类:完整类名,使用通配符 --> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.xiaog.service.*.*(..))" /> </aop:config> </beans>
(3)spring-mvc.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: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-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 1.启动自动扫描 --> <context:component-scan base-package="com.xiaog.controller" /> <!-- 2.注册MVC注解驱动 --> <mvc:annotation-driven /> <!-- 3.配置静态资源 css js imgs --> <mvc:resources location="/resources/**" mapping="/resources"/> <mvc:resources location="/webapp/static/**" mapping="/webapp/static"/> <!-- 4.配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name = "prefix" value="/" /><!-- 前缀 --> <property name = "suffix" value = ".jsp" /><!-- 后缀 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> </beans>
(4)mybatis-config.xml
<?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> <typeAliases> <package name="com.xiaog.entity" /> </typeAliases> </configuration>
(5)logback.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- 控制台输出 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- 日志输出编码 --> <!-- <Encoding>UTF-8</Encoding> --> <layout class="ch.qos.logback.classic.PatternLayout"> <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符--> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n </pattern> </layout> </appender> <!-- 日志输出级别 --> <root level="INFO"> <appender-ref ref="STDOUT" /> </root> <!-- 打印sql语句 --> <logger name="com.xiaog.dao" level="DEBUG" /> </configuration>
(6)jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssjdbc?useSSL=false&useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=root
(7)UserMapper.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.xiaog.dao.UserDao" > <resultMap id="BaseResultMap" type="User" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="username" property="username" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > id, username, password </sql> <select id="getOne" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from user where id = #{id,jdbcType=INTEGER} </select> <select id="getList" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from user <where> <if test="username != null" > and username = #{username,jdbcType=VARCHAR} </if> <if test="password != null" > and password = #{password,jdbcType=VARCHAR} </if> </where> </select> <delete id="delete" parameterType="java.lang.Integer" > delete from user where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="User" > insert into user <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="username != null" > username, </if> <if test="password != null" > password, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="username != null" > #{username,jdbcType=VARCHAR}, </if> <if test="password != null" > #{password,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="update" parameterType="User" > update user <set > <if test="username != null" > username = #{username,jdbcType=VARCHAR}, </if> <if test="password != null" > password = #{password,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> </mapper>
(8)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_3_0.xsd" version="3.0"> <display-name>testssm</display-name> <!-- spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-context.xml</param-value> </context-param> <!-- spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 字符编码过滤器 spring web自动提供一个 --> <filter> <filter-name>encodingFilter</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>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- spring mvc 配置 【中央控制器/前端控制器/总控】 --> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置Spring mvc下的配置文件的位置和名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 可以配置扩展名,*.do --> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 添加日志监听器 --> <context-param> <param-name>logbackConfigLocation</param-name> <param-value>classpath:logback.xml</param-value> </context-param> <listener> <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
6.实体类User
package com.xiaog.entity; public class User { private Integer id; private String username; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + "]"; } }
7.核心Dao接口及其实现
package com.xiaog.core.dao; import java.util.List; public interface CoreDao<T> { int insert(T t); int delete(int id); int update(T t); T getOne(int id); List<T> getList(T t); }
package com.xiaog.core.dao.impl; import java.lang.reflect.ParameterizedType; import java.util.List; import org.mybatis.spring.support.SqlSessionDaoSupport; import com.xiaog.core.dao.CoreDao; public class CoreDaoImpl<T> extends SqlSessionDaoSupport implements CoreDao<T> { private Class<T> clazz; private static String PREFIX; @SuppressWarnings("unchecked") public CoreDaoImpl() { this.clazz = (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; PREFIX = "com.xiaog.dao."+clazz.getSimpleName()+"Dao."; } @Override public int insert(T t) { return super.getSqlSession().insert(PREFIX+"insert",t); } @Override public int delete(int id) { return super.getSqlSession().delete(PREFIX+"delete", id); } @Override public int update(T t) { return super.getSqlSession().update(PREFIX+"update", t); } @Override public T getOne(int id) { return super.getSqlSession().selectOne(PREFIX+"getOne", id); } @Override public List<T> getList(T t) { return super.getSqlSession().selectList(PREFIX+"getList", t); } }
8.模块dao接口及其实现
package com.xiaog.dao; import com.xiaog.core.dao.CoreDao; import com.xiaog.entity.User; public interface UserDao extends CoreDao<User> { }
package com.xiaog.dao.impl; import org.springframework.stereotype.Repository; import com.xiaog.core.dao.impl.CoreDaoImpl; import com.xiaog.dao.UserDao; import com.xiaog.entity.User; @Repository public class UserDaoImpl extends CoreDaoImpl<User> implements UserDao { }
9.service接口及其实现
package com.xiaog.service; import com.xiaog.entity.User; public interface UserService { User login(User user); }
package com.xiaog.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.xiaog.dao.UserDao; import com.xiaog.entity.User; import com.xiaog.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public User login(User user) { List<User> users = userDao.getList(user); if(users!=null && users.size()>0) { return users.get(0); }else { return null; } } }
10.controller
package com.xiaog.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 com.xiaog.entity.User; import com.xiaog.service.UserService; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; private final static Logger logger = LoggerFactory.getLogger(UserController.class); @RequestMapping(value = "/login",params= {"username","password","username!=","password!="}) public String login(Model model,User user) { user = userService.login(user); logger.info("user="+user); model.addAttribute("user", user); return "result"; } }
11.测试登录的jsp页面
(1)index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="user/login" method="post"> <div> <label>username</label> <input type="text" name="username"/> </div> <div> <label>password</label> <input type="password" name="password"/> </div> <div> <input type="submit" value="登录"> </div> </form> </body> </html>
(2)result.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!doctype html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> username=${user} </body> </html>
12.启动项目
项目右击-->run as-->maven build->在Goals中填tomcat7:run,然后apply,run就启动项目了
浏览器输入http://localhost:9999/testssm