标签:
step1)建立数据库和表字段
step2)安装 mybatis generator:download from https://github.com/mybatis/generator, (具体的安装 detail 不再累述,自行google)
step3)安装完后,在eclipse中执行如下操作(当然,你要先建立好web proj);(t3)
step4)修改generatorConfig.xml 中的相应配置信息,右键该文件,点击 generate MyBatis/iBatis artifacts,生成相应的 ORM 映射文件;
对以上生成文件的分析(Analysis):
A1)TStudentMapper 是个接口:它其实是作为 dao 层,数据访问层,你可以将其 放置在 dao package中,它没有实现类,它其中的方法具体实现 由 TStudentMapper.xml 中的XML 配置元素来实现;(这里很容易理解,Apache Digester库 通过反射可以将 XML元素 转换为java类对象),这种实现就是与底层数据库进行交互(厉害);A2)TStudent :就是一个 model 或 pojo,你可以将其 移入到 model 或 pojo package下;
package com.mybatis.service; import com.mybatis.model.Student; public interface StudentService { void insertStudent(int id, String username); public Student getStudentById(int Id); }
package com.mybatis.serviceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mybatis.dao.StudentMapper; import com.mybatis.model.Student; import com.mybatis.service.StudentService; @Service public class StudentServiceImpl implements StudentService{ @Autowired private StudentMapper studentMapper; @Override public void insertStudent(int id, String username) { Student stu = new Student(id, username); } @Override public Student getStudentById(int id) { return studentMapper.selectByPrimaryKey(id); } }
<?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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.mybatis" /> <!-- 引入 jdbc 配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <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="initialSize" value="${initialSize}" /> <!-- 连接池最大数量 --> <property name="maxTotal" value="${maxTotal}" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}" /> <!-- 获取连接最大等待时间 --> <property name="maxWaitMillis" value="${maxWait}" /> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/mybatis/orm/*.xml" /> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.mybatis.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
3.1)log4j.properties(log4j 日志属性文件)#定义LOG输出级别 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%n3.2)jdbc.properties(jdbc属性文件)driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/t_mybatis username=root password=root #定义初始连接数 initialSize=0 #定义最大连接数 maxTotal=20 #定义最大空闲 maxIdle=20 #定义最小空闲 minIdle=1 #定义最长等待时间 maxWait=60000
package com.mybatis.test; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.mybatis.model.Student; import com.mybatis.service.StudentService; @RunWith(SpringJUnit4ClassRunner.class) //表示继承了SpringJUnit4ClassRunner类 @ContextConfiguration(locations = {"classpath:spring-mybatis.xml"}) public class TestMyBatis { @Resource private StudentService studentService; @Test public void test1() { Student stu = studentService.getStudentById(1); System.out.println(" the name is " + stu.getName()); } }
step1)V-View视图层: 建立jsp 文件 渲染 服务器响应的结果;(t6)<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>测试</title> </head> <body> ${student.name} </body> </html>
step2)C-Controller 控制器层:建立Controller java 类,对前台请求路径进行路由映射;package com.mybatis.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; 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 org.springframework.web.bind.annotation.RequestMethod; import com.mybatis.model.Student; import com.mybatis.service.StudentService; @Controller @RequestMapping(value="/stu") public class StudentController { @Resource private StudentService studentService; @RequestMapping(value="/showUser", method=RequestMethod.GET) public String toIndex(HttpServletRequest request, Model model){ int userId = Integer.parseInt(request.getParameter("id")); Student student = this.studentService.getStudentById(userId); model.addAttribute("student", student); return "showUser"; } }
<?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:p="http://www.springframework.org/schema/p" 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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.mybatis.controller" /> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 --> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> </beans>
<?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>MyBatis SpringMVC Integration</display-name> <!-- Spring和mybatis的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- Spring MVC servlet --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
Spring4.2.6+SpringMVC4.2.6+MyBatis3.4.0 整合
标签:
原文地址:http://blog.csdn.net/pacosonswjtu/article/details/51693186