1 环境准备
STS 开发工具, Spring提供的eclipse插件
替代myeclipse
免费,自带maven插件
www.springsource.org
spring-tool-suite-3.1.0....x86_64,zip
STS.exe打开
tomcat7
jdk7
mybatis generator tool 需要自己下载
mybatis-generator-core-1.3.2.jar
生成语句
java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
mybatis核心包在maven里面可以下载
mysql客户端软件
Navicat Premium
表已经建好
2 使用mybatis generator
通过mybatis generator,根据数据表,以及配置文件generator.xml,生成映射文件
把生成后的文件放在src目录
generator.xml
<?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>
<!-- 数据库驱动包位置 -->
<!-- <classPathEntry location="D:\software\lib\mysql-connector-java-5.1.21.jar" /> -->
<classPathEntry location="C:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 数据库链接URL、用户名、密码 -->
<!-- <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/sy" userId="sypro" password="sypro"> -->
<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成模型的包名和位置 -->
<javaModelGenerator targetPackage="sy.model" targetProject="D:\study\mybatis\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成的映射文件包名和位置 -->
<sqlMapGenerator targetPackage="sy.mapping" targetProject="D:\study\mybatis\src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 生成DAO的包名和位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="sy.dao" targetProject="D:\study\mybatis\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
<table tableName="tbug" domainObjectName="Bug" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
<table tableName="tmenu" domainObjectName="Menu" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
<table tableName="tonline" domainObjectName="Online" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
<table tableName="tresource" domainObjectName="Resource" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
<table tableName="trole" domainObjectName="Role" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
<table tableName="trole_tresource" domainObjectName="RoleResource" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
<table tableName="tuser" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
<table tableName="tuser_trole" domainObjectName="UserRole" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
</context>
</generatorConfiguration>
然后在cmd下运行
java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
路径不能带中文
生成了各个表的Mapper.xml文件,dao文件,model文件
里面有增删改查的语句
之后直接放入maven项目目录
src\main\java\sy\mapping
BugMapper.xml
MenuMapper.xml
OnlineMapper.xml
ResourceMapper.xml
RoleMapper.xml
RoleResourceMapper.xml
UserMapper.xml
UserRoleMapper.xml
src\main\java\sy\dao
BugMapper.java
MenuMapper.java
OnlineMapper.java
ResourceMapper.java
RoleMapper.java
RoleResourceMapper.java
UserMapper.java
UserRoleMapper.java
src\main\java\sy\model
Bug.java
Menu.java
Online.java
Resource.java
Role.java
RoleResource.java
Userjava
UserRole.java
3 创建mave项目
http://blog.csdn.net/adeyi/article/details/17259479
new Maven Project
Select Archetype
Catalog, All catalogs
Filter:webapp
org.apache.maven.archetypes
Enter artifact id
Group Id, sy.testmybatis
Artifact Id, sy.testmybatis
Finish
右键propperties里面把编码设置成utf-8先
Project facets
Java -> 1.7 版本
Dynamic web module -> 3.0
Java Build Path
Edit, java1.7
可以看到
src/main/java
src/main/resource
还存在src/main/webapp
打开pom.xml
在网上复制
首先整合spring和mybatis
search.maven.org
搜索
1 spring-core
找到spring3.2
就可以找到maven的pom配置
复制后放入我们自己的pom.xml里面
2 mybatis
找到3.1.1
同样复制pom配置
3 mybatis-spring
整合两者的包
mybatis里面有对spring的支持
找到1.1.1版本,复制pom
4 mysql-connector-java
找到5.1.21, 复制pom
5 junit
找到4.11, 复制pom
6 druid
阿里的druid数据源,好比c3p0,dbcp
版本0.2.9
7 org.aspectj
选择aspectjweaver1.7.1, 复制pom
8 spring-test
spring的测试方法,属于spring3.2.0 release 复制pom
9 spring-webmvc
版本3.2.0 复制pom
10 jackson-mapper-asl
json支持 1.9.11 复制pom
11 commons-fileupload
文件上传肯定要apache的fileupload 1.2.2 复制pom
12 javax servlet
SpringMVC的controller要用httprequest
版本3.0-alpha-1 复制pom
13 log4j
添加针对mybatis显示sql语句的日志
版本1.2.17 复制pom
14 fastjson
阿里巴巴做的json处理包
版本1.1.26 复制pom
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<!– The Basics 这里都是创建时生成的 –>
<groupId>sy.testmybatis</groupId>
<artifactId>testmybatis</artifactId>
<version>0.0.1</version>
<name>testmybatis Maven Webapp</name>
<url>http://maven.apache.org</url>
–>
<dependencies>
<!– Spring的依赖 这里添加后,spring-core包自动添加到Maven Dependencies里面了
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<!-- spring的测试方法,属于spring3.2.0 release -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<!-- springmvc,属于spring3.2.0 release -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<!-- Mybatis依赖包, mybatis的jar包也自动添加-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.1.1</version>
</dependency>
<!-- 整合依赖包, 会添加好很多jar包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.1.1</version>
</dependency>
<!-- mysql驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<!-- junit驱动包 设置scope,表示开发时用,将来生成war时不用-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- druid数据源依赖包-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>0.2.9</version>
</dependency>
<!-- aspectj面向切面的框架依赖包-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.1</version>
</dependency>
<!-- jackson -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency>
<!-- sprinmvc文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<!-- javax.servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.26</version>
</dependency>
</dependencies>
<build>
</build>
</project>
配置文件都在src/main/resource
1 spring的配置文件
spring.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" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- 引入属性文件 -->
<context:property-placeholder location="classpath:config.properties" />
<!-- 自动扫描(自动注入) -->
<context:component-scan base-package="sy.service" />
</beans>
2 config.properties
#hibernate.dialect=org.hibernate.dialect.OracleDialect
#driverClassName=oracle.jdbc.driver.OracleDriver
#validationQuery=SELECT 1 FROM DUAL
#jdbc_url=jdbc:oracle:thin:@localhost:1521:orcl
#jdbc_username=sypro
#jdbc_password=sypro
#前两句其实都可以不用,
#阿里的druid数据源会根据url自动判断数据库类型
hibernate.dialect=org.hibernate.dialect.MySQLDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/sy?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=sypro
jdbc_password=sypro
#hibernate.dialect=org.hibernate.dialect.SQLServerDialect
#driverClassName=net.sourceforge.jtds.jdbc.Driver
#validationQuery=SELECT 1
#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy
#jdbc_username=sa
#jdbc_password=123456
#hibernate.dialect=org.hibernate.dialect.DerbyDialect
#driverClassName=org.apache.derby.jdbc.EmbeddedDriver
#validationQuery=SELECT 1
#jdbc_url=jdbc:derby:sy;create=true
#jdbc_username=sypro
#jdbc_password=sypro
#jndiName=java:comp/env/dataSourceName
hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=true
sessionInfoName=sessionInfo
uploadFieldName=filedata
uploadFileMaxSize=20971520
uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid
uploadDirectory=attached
3 整合spring,mybatic用配置文件
spring-mybatis.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
<!-- JNDI方式配置数据源,当tomcat里面配置了数据源就可以用jndi引入,否则需要自己下面引入 -->
<!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> -->
<!-- 配置数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
<!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->
<property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" />
<!-- 监控数据库 -->
<!-- <property name="filters" value="stat" /> -->
<property name="filters" value="mergeStat" />
</bean>
<!-- myBatis文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
<property name="mapperLocations" value="classpath:sy/mapping/*.xml" />
</bean>
<!-- 自动扫描dao目录, 省掉Configuration.xml里的手工配置 -->
<!-- 引用sqlSessionFactory, 这里有个坑,使用sqlSessionFactoryBeanName属性,而不是sqlSessionFactoryBean
否则会先启动本扫描,造成db.properties还未加载,发生错误-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="sy.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 注解方式配置事务 -->
<!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
<!-- 拦截器方式配置事务 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="append*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="repair" propagation="REQUIRED" />
<tx:method name="delAndRepair" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="load*" propagation="SUPPORTS" />
<tx:method name="search*" propagation="SUPPORTS" />
<tx:method name="datagrid*" propagation="SUPPORTS" />
<tx:method name="*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* sy.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
</aop:config>
<!-- 配置druid监控spring jdbc -->
<bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
</bean>
<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
<property name="patterns">
<list>
<value>sy.service.*</value>
</list>
</property>
</bean>
<aop:config>
<aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
</aop:config>
</beans>
4 springmvc配置文件
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
<context:component-scan base-package="sy.controller" />
<!-- 避免IE执行AJAX时,返回JSON出现下载文件,告诉ie服务器传的是text -->
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
</list>
</property>
</bean>
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀, 根目录就是WebRoot/ -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />
<!-- 文件上传使用-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<value>32505856</value><!-- 上传文件大小限制为31M,31*1024*1024 -->
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
</beans>
5 整合springmvc
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>mybatis</display-name>
<!--主要的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
</context-param>
<filter>
<description>字符集过滤器</description>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<description>字符集编码</description>
<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>
<listener>
<description>spring监听器</description>
<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 ,配置文件所在,前台页面后缀映射使用*.do访问-->
<servlet>
<description>spring mvc servlet</description>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>spring mvc 配置文件</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置session超时时间,单位分钟 -->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
6 log4j配置文件
//开启日志打印,生产环境不用debug
log4j.rootLogger=DEBUG,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=mybatis.log
log4j.appender.File.MaxFileSize=10MB
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,SSS}][%c]%m%n
4 测试
整合完成,测试整合结果
src\main\java\sy\service
package sy.service;
public interface UserServiceI {
public User getUserById(String id);
List<User> getAll();
List<User> getAll2();
List<User> getAll3();
}
package sy.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//自动扫描使用的注解
@Service("userService")
public class UserServiceImpl implements UserServiceI {
private UserMapper userMapper;
public UserMapper getUserMapper() {
return userMapper;
}
//注入
@Autowired
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
//UserMapper.xml里面写好了sql语句
@Override
public User getUserById(String id) {
return userMapper.selectByPrimaryKey(id);
}
@Override
public List<User> getAll() {
return userMapper.getAll();
}
@Override
public List<User> getAll2() {
return userMapper.getAll2();
}
@Override
public List<User> getAll3() {
return userMapper.getAll3();
}
}
package sy.dao;
public interface UserMapper {
int deleteByPrimaryKey(String id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
//添加自己的查询
List<User> getAll();
List<User> getAll2();
List<User> getAll3();
}
src\main\java\sy\mapping
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="sy.dao.UserMapper">
<resultMap id="BaseResultMap" type="sy.model.User">
<id column="ID" property="id" jdbcType="VARCHAR" />
<result column="CREATEDATETIME" property="createdatetime" jdbcType="TIMESTAMP" />
<result column="MODIFYDATETIME" property="modifydatetime" jdbcType="TIMESTAMP" />
<result column="NAME" property="name" jdbcType="VARCHAR" />
<result column="PWD" property="pwd" jdbcType="VARCHAR" />
<result column="CREATE_TIME" property="createTime" jdbcType="DATE" />
<result column="UPDATE_TIME" property="updateTime" jdbcType="DATE" />
</resultMap>
<sql id="Base_Column_List">
ID, CREATEDATETIME, MODIFYDATETIME, NAME, PWD, CREATE_TIME, UPDATE_TIME
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String">
select
<include refid="Base_Column_List" />
from tuser
where ID = #{id,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String">
delete from tuser
where ID = #{id,jdbcType=VARCHAR}
</delete>
<insert id="insert" parameterType="sy.model.User">
insert into tuser (ID, CREATEDATETIME, MODIFYDATETIME,
NAME, PWD, CREATE_TIME,
UPDATE_TIME)
values (#{id,jdbcType=VARCHAR}, #{createdatetime,jdbcType=TIMESTAMP}, #{modifydatetime,jdbcType=TIMESTAMP},
#{name,jdbcType=VARCHAR}, #{pwd,jdbcType=VARCHAR}, #{createTime,jdbcType=DATE},
#{updateTime,jdbcType=DATE})
</insert>
<insert id="insertSelective" parameterType="sy.model.User">
insert into tuser
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
ID,
</if>
<if test="createdatetime != null">
CREATEDATETIME,
</if>
<if test="modifydatetime != null">
MODIFYDATETIME,
</if>
<if test="name != null">
NAME,
</if>
<if test="pwd != null">
PWD,
</if>
<if test="createTime != null">
CREATE_TIME,
</if>
<if test="updateTime != null">
UPDATE_TIME,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=VARCHAR},
</if>
<if test="createdatetime != null">
#{createdatetime,jdbcType=TIMESTAMP},
</if>
<if test="modifydatetime != null">
#{modifydatetime,jdbcType=TIMESTAMP},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="pwd != null">
#{pwd,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
#{createTime,jdbcType=DATE},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=DATE},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="sy.model.User">
update tuser
<set>
<if test="createdatetime != null">
CREATEDATETIME = #{createdatetime,jdbcType=TIMESTAMP},
</if>
<if test="modifydatetime != null">
MODIFYDATETIME = #{modifydatetime,jdbcType=TIMESTAMP},
</if>
<if test="name != null">
NAME = #{name,jdbcType=VARCHAR},
</if>
<if test="pwd != null">
PWD = #{pwd,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
CREATE_TIME = #{createTime,jdbcType=DATE},
</if>
<if test="updateTime != null">
UPDATE_TIME = #{updateTime,jdbcType=DATE},
</if>
</set>
where ID = #{id,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="sy.model.User">
update tuser
set CREATEDATETIME = #{createdatetime,jdbcType=TIMESTAMP},
MODIFYDATETIME = #{modifydatetime,jdbcType=TIMESTAMP},
NAME = #{name,jdbcType=VARCHAR},
PWD = #{pwd,jdbcType=VARCHAR},
CREATE_TIME = #{createTime,jdbcType=DATE},
UPDATE_TIME = #{updateTime,jdbcType=DATE}
where ID = #{id,jdbcType=VARCHAR}
</update>
<!--添加自己的查询-->
<!--user和role多对多关系,通过user要知道其角色,需要中间表UserRole-->
<!--传入的是string类型,返回的是UserRole-->
<select id="selectUserRole" parameterType="java.lang.String" resultType="sy.model.UserRole">
SELECT
tuser_trole.ID,
tuser_trole.ROLE_ID,
tuser_trole.USER_ID
FROM
tuser_trole
where tuser_trole.user_id=#{id,jdbcType=VARCHAR}
</select>
<!--继承上面的BaseResultMap,使用其基础字段,然后再添加 list<UserRoles>-->
<!--把getAll的ID作为参数,传入下一个查询selectUserRole,返回的是list-->
<resultMap type="sy.model.User" id="userResultMap" extends="BaseResultMap">
<collection property="userRoles" column="ID" javaType="list" select="selectUserRole" />
</resultMap>
<select id="getAll" resultMap="userResultMap">
select ID, CREATEDATETIME, MODIFYDATETIME, NAME, PWD from tuser
</select>
<!--上一个查询效率太差,应该使用join, 然后映射成User对象-->
<resultMap type="sy.model.User" id="userResultMap2" extends="BaseResultMap">
<collection property="userRoles" javaType="list" ofType="sy.model.UserRole">
<id property="id" column="userrole_id" />
<result column="role_id" property="roleId" />
<result property="userId" column="user_id" />
</collection>
</resultMap>
<select id="getAll2" resultMap="userResultMap2">
SELECT
tuser.ID,
tuser.CREATEDATETIME,
tuser.MODIFYDATETIME,
tuser.`NAME`,
tuser.PWD,
tuser.CREATE_TIME,
tuser.UPDATE_TIME,
tuser_trole.ID userrole_id,
tuser_trole.ROLE_ID role_id,
tuser_trole.USER_ID user_id
FROM
tuser
JOIN tuser_trole ON tuser.ID = tuser_trole.USER_ID
</select>
<!--UserRole里面引入Role属性,就可以直接拿到User关联的Role了-->
<resultMap type="sy.model.User" id="userResultMap3" extends="BaseResultMap">
<collection property="userRoles" javaType="list" ofType="sy.model.UserRole">
<id property="id" column="userrole_id" />
<result column="role_id" property="roleId" />
<result property="userId" column="user_id" />
<!--映射单个对象用association-->
<association property="role" javaType="sy.model.Role">
<id property="id" column="role_id" />
<result property="text" column="role_text" />
</association>
</collection>
</resultMap>
<select id="getAll3" resultMap="userResultMap3">
SELECT
tuser.ID,
tuser.CREATEDATETIME,
tuser.MODIFYDATETIME,
tuser.`NAME`,
tuser.PWD,
tuser.CREATE_TIME,
tuser.UPDATE_TIME,
tuser_trole.ID userrole_id,
tuser_trole.ROLE_ID role_id,
tuser_trole.USER_ID user_id,
trole.ID role_id,
trole.TEXT role_text
FROM
tuser
JOIN tuser_trole ON tuser.ID = tuser_trole.USER_ID
JOIN trole ON tuser_trole.ROLE_ID = trole.ID
</select>
</mapper>
package sy.model;
public class User {
//User和Role的多对多关系,用中间表解决
//这里先做一个User对应多个UserRole
//通过中间关系表,拿到Role
private List<UserRole> userRoles;
public List<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(List<UserRole> userRoles) {
this.userRoles = userRoles;
}
private String id;
private Date createdatetime;
private Date modifydatetime;
private String name;
private String pwd;
private Date createTime;
private Date updateTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public Date getCreatedatetime() {
return createdatetime;
}
public void setCreatedatetime(Date createdatetime) {
this.createdatetime = createdatetime;
}
public Date getModifydatetime() {
return modifydatetime;
}
public void setModifydatetime(Date modifydatetime) {
this.modifydatetime = modifydatetime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd == null ? null : pwd.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
package sy.model;
public class Role {
private String id;
private String text;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text == null ? null : text.trim();
}
}
中间表,User和Role的对应关系
package sy.model;
public class UserRole {
private Role role;
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
private String id;
private String roleId;
private String userId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId == null ? null : roleId.trim();
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId == null ? null : userId.trim();
}
}
src\main\java\sy\controller
package sy.controller;
//自动扫描使用的注解
@Controller
@RequestMapping("/userController")
public class UserController {
private UserServiceI userService;
public UserServiceI getUserService() {
return userService;
}
@Autowired
public void setUserService(UserServiceI userService) {
this.userService = userService;
}
//这里不应该写*.do, 要写在配置文件中
//rest格式访问url
@RequestMapping("/{id}/showUser")
public String showUser(@PathVariable String id, HttpServletRequest request) {
User u = userService.getUserById(id);
request.setAttribute("user", u);
return "showUser";
}
}
src\test\java\sy\test
Spring的测试方法,需要添加pom依赖spring-test
package sy.test;
import java.util.List;
import org.apache.log4j.Logger;
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 sy.model.User;
import sy.service.UserServiceI
import com.alibaba.fastjson.JSON;
//当没有spring-test,我们测试junit时
//@Before
//public void before(){
// Application ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});
// UserService userServer = (UserServiceI)ac.getBean("userService");
//}
//@Test
//public void test1(){
// User u=userServbice.getUserById("1");
//}
//使用spring-test, 就只需要注解@RunWith,继承SpringJUnit4ClassRunner
//指定spring的配置文件,生成上下文
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-mybatis.xml" })
public class TestMybatis {
private static final Logger logger = Logger.getLogger(TestMybatis.class);
private UserServiceI userService;
public UserServiceI getUserService() {
return userService;
}
@Autowired
public void setUserService(UserServiceI userService) {
this.userService = userService;
}
@Test
public void test1() {
User u = userService.getUserById("1");
//JSON把对象转换成json字符串方便阅读
logger.info(JSON.toJSONStringWithDateFormat(u, "yyyy-MM-dd HH:mm:ss"));
}
@Test
public void test2() {
List<User> l = userService.getAll();
logger.info(JSON.toJSONStringWithDateFormat(l, "yyyy-MM-dd HH:mm:ss"));
}
@Test
public void test3() {
List<User> l = userService.getAll2();
logger.info(JSON.toJSONStringWithDateFormat(l, "yyyy-MM-dd HH:mm:ss"));
}
@Test
public void test4() {
List<User> l = userService.getAll3();
logger.info(JSON.toJSONStringWithDateFormat(l, "yyyy-MM-dd HH:mm:ss"));
}
}
测试中发现缺少面向切面的框架aspect包,
那么去pom中添加
之后发现缺少包的错误都需要这么处理
src\main\webapp
showUser.do
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>${user.name}
</body>
</html>
5 如何发布到tomcat7
双击tomcat server,稍作配置
Use Tomcat installation(takes control o tomcat installation)
把server path转到tomcat的安装路径
编译maven项目
run as maven install
在写pom的时候,注意包的前后顺序
比如最先加载所有Spring3.2的包,
否则可能先加载到其他版本
发布到tomcat7
访问
localhost:8080/testmybatis/userController/1/showUser.do
6 STS编译Maven时出现的问题
打包项目:
运行mvn clean
然后workspace里面对testmybatis项目直接打压缩包,比如.7z
导入maven项目
拿到压缩包,导入STS
project clean
运行mvn install
7 简化
可以在User里面直接引用List<Role>, 而不是引用List<UserRole>
<resultMap type="sy.model.User" id="userResultMap4" extends="BaseResultMap">
<collection property="roles" javaType="list" ofType="sy.model.Role">
<id property="id" column="role_id" />
<result property="text" column="role_text" />
</collection>
</resultMap>
<select id="getAll4" resultMap="userResultMap4">
SELECT
tuser.ID,
tuser.CREATEDATETIME,
tuser.MODIFYDATETIME,
tuser.`NAME`,
tuser.PWD,
tuser.CREATE_TIME,
tuser.UPDATE_TIME,
tuser_trole.ID ,
tuser_trole.ROLE_ID ,
tuser_trole.USER_ID ,
trole.ID role_id,
trole.TEXT role_text
FROM
tuser
JOIN tuser_trole ON tuser.ID = tuser_trole.USER_ID
JOIN trole ON tuser_trole.ROLE_ID = trole.ID
</select>