1.maven添加各种依赖包
<!-- 数据库连接池 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!-- Mybatis与Spring的包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- Mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.2</version> </dependency> <!-- Spring jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.6.RELEASE</version> </dependency> <!-- 动态代理 --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency> <!-- 数据库驱动 --> <dependency> <groupId> mysql</groupId> <artifactId> mysql-connector-java</artifactId> <version> 5.0.5</version> </dependency> <!-- Spring框架 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.6.RELEASE</version> </dependency> <!-- SpringMVC框架 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.6.RELEASE</version> </dependency>
2.配置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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.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"> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <!-- 数据库驱动 --> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <!-- 连接URL串 --> <property name="jdbcUrl" value="url" /> <!-- 连接用户名 --> <property name="user" value="user" /> <!-- 连接密码 --> <property name="password" value="pass" /> <!-- 初始化连接池时连接数量为5个 --> <property name="initialPoolSize" value="5" /> <!-- 允许最小连接数量为5个 --> <property name="minPoolSize" value="5" /> <!-- 允许最大连接数量为20个 --> <property name="maxPoolSize" value="20" /> <!-- 允许连接池最大生成100个PreparedStatement对象 --> <property name="maxStatements" value="100" /> <!-- 连接有效时间,连接超过3600秒未使用,则该连接丢弃 --> <property name="maxIdleTime" value="3600" /> <!-- 连接用完时,一次产生的新连接步进值为2 --> <property name="acquireIncrement" value="2" /> <!-- 获取连接失败后再尝试10次,再失败则返回DAOException异常 --> <property name="acquireRetryAttempts" value="10" /> <!-- 获取下一次连接时最短间隔600毫秒,有助于提高性能 --> <property name="acquireRetryDelay" value="600" /> <!-- 检查连接的有效性,此处小弟不是很懂什么意思 --> <property name="testConnectionOnCheckin" value="true" /> <!-- 每个1200秒检查连接对象状态 --> <property name="idleConnectionTestPeriod" value="1200" /> <!-- 获取新连接的超时时间为10000毫秒 --> <property name="checkoutTimeout" value="10000" /> </bean> <!-- 创建SqlSessionFactory,同时指定数据源 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:configuration.xml" /> <property name="dataSource" ref="dataSource" /> </bean> <!-- 自动创建mybatis的代理类的配置 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ray.model.mapper" /> </bean> <mvc:annotation-driven /> <!-- 把标记了@Controller注解的类转换为bean --> <context:component-scan base-package="com.ray.services" /> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- Spring MVC的跳转配置(我猜的) --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
3.配置web.xml
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring.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>
4.配置mybatis自动生成实体(运行maven install的时候)
首先配置pom.xml
<!--配置常用的属性--> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <entity.target.dir>src/main/java/</entity.target.dir> <dao.resources.dir>src/main/resources/</dao.resources.dir> </properties> <!--自动生成--> <build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <dependencies> <!-- 数据库驱动 --> <dependency> <groupId> mysql</groupId> <artifactId> mysql-connector-java</artifactId> <version> 5.0.5</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.4</version> </dependency> </dependencies> <executions> <execution> <id>Generate MyBatis Artifacts</id> <phase>package</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <verbose>false</verbose> <overwrite>false</overwrite> <configurationFile> src/main/resources/mybatis-generator.xml</configurationFile> </configuration> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <encoding>UTF-8</encoding> <source>1.5</source> <target>1.5</target> </configuration> </plugin> </plugins> </build>
配置mybatis-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> <context id="DB2Tables" targetRuntime="MyBatis3" defaultModelType="flat"> <plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin"> <property name="searchString" value="[e|E]xample$" /> <property name="replaceString" value="Criteria" /> </plugin> <commentGenerator> <property name="suppressDate" value="true" /> </commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/ray" userId="ray" password="123456"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- generate Model --> <javaModelGenerator targetPackage="com.ray.model" targetProject="${entity.target.dir}"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 自动生成xml(但是好像一直没有生成功,反正也不用xml) --> <sqlMapGenerator targetPackage="com.ray.model.mapper" targetProject="${dao.resources.dir}"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 自动生成mapper接口, 可以是 ANNOTATEDMAPPER(注解), XMLMAPPER(xml), MIXEDMAPPER(不知道) --> <javaClientGenerator type="ANNOTATEDMAPPER" targetPackage="com.ray.model.mapper" implementationPackage="com.ray.model.mapper.impl" targetProject="${entity.target.dir}"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <table tableName="user" domainObjectName="User"> </table> </context> </generatorConfiguration>
5.mybatis配置configuration.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd"> <configuration> <settings> <!-- 全局映射器启用缓存 --> <setting name="cacheEnabled" value="true" /> <!-- 查询时,关闭关联对象即时加载以提高性能 --> <setting name="lazyLoadingEnabled" value="true" /> <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 --> <setting name="aggressiveLazyLoading" value="false" /> <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 --> <setting name="multipleResultSetsEnabled" value="true" /> <!-- 允许使用列标签代替列名 --> <setting name="useColumnLabel" value="true" /> <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 --> <setting name="useGeneratedKeys" value="true" /> <!-- 给予被嵌套的resultMap以字段-属性的映射支持 --> <setting name="autoMappingBehavior" value="FULL" /> <!-- 对于批量更新操作缓存SQL以提高性能 --> <setting name="defaultExecutorType" value="BATCH" /> <!-- 数据库超过25000秒仍未响应则超时 --> <setting name="defaultStatementTimeout" value="25000" /> </settings> <!-- 全局别名设置,在映射文件中只需写别名,而不必写出整个类路径 --> <typeAliases> <typeAlias alias="User" type="com.ray.model.User" /> </typeAliases> <!-- 非注解的sql映射文件配置,如果使用mybatis注解,该mapper无需配置,但是如果mybatis注解中包含@resultMap注解,则mapper必须配置,给resultMap注解使用 --> <!-- <mappers> <mapper resource="persist/test/orm/test.xml" /> </mappers> --> </configuration>
6.使用
package com.ray.services; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.ray.model.mapper.UserMapper; @Controller public class Test { @Autowired private UserMapper mapper; /** * 测试有多少条数据 * @param response */ @RequestMapping("/getcount.do") public void count(HttpServletResponse response){ PrintWriter pw = null; try { pw = response.getWriter(); pw.write("count:"+mapper.countByExample(null)); } catch (IOException e) { e.printStackTrace(); }finally{ if(pw != null){ pw.close(); } } } public UserMapper getMapper() { return mapper; } public void setMapper(UserMapper mapper) { this.mapper = mapper; } }
虽然也需要用xml文档来进行配置,但是感觉用注解还是方便了好多,具体代码项目地址(这个项目配置了最基本的环境,但是项目是分模块的)