项目说明:
(1) 本例采用 maven web 工程做例子讲解
(2) 利用mybaits 提供的代码生成工具自动生成代码(dao接口,sql mapper映射文件,pojo数据库映射类)
(3) 数据库用 mysql
项目构建:
一,新建maven web 工程
网上有很多详细的教程,初学者可以点这里跳转学习:eclipse创建maven工程
本例项目结构如下,待会再一步一步讲解:
二,引入需要的jar包到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>SpringMVCMaven</groupId> <artifactId>SpringMVCMaven</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SpringMVCMaven</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.3.0.RELEASE</spring.version> <jackson.version>2.6.5</jackson.version> <fastjson.version>1.2.23</fastjson.version> <mybatis.version>3.3.0</mybatis.version> <mybatis-spring.version>1.2.3</mybatis-spring.version> <mysql.connector.version>5.1.29</mysql.connector.version> </properties> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/libs-milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.2</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- mybatis start --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!-- fastjson --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>com.maven.web</finalName> </build> </project>
三,配置web.xml,加入spring + springMvc 核心监听器,配置如下:
<?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"> <!-- 设置Spring容器加载所有的配置文件的路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:Spring-config.xml</param-value> </context-param> <!-- 加载Spring容器配置 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class> org.springframework.web.context.ContextCleanupListener</listener-class> </listener> <!-- 字符编码过滤器 --> <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> <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> <!-- 配置SpringMVC核心控制器 --> <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-servlet.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> <url-pattern>/</url-pattern> </servlet-mapping> <!-- session超时设置 --> <session-config> <session-timeout>30</session-timeout> </session-config> <!-- 项目启动首页 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
大家可以看到,在web.xml中加入了两个配置文件:
classpath:Spring-config.xml :这个是Spring的核心配置文件,用于管理bean,集成其他框架等等
classpath:Spring-servlet.xml:这个是SpringMvc的核心配置文件
四,Spring-config.xml ,,与mybatis集成,配置如下:
<?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" 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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 扫描注解 --> <context:component-scan base-package="com.maven.web"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 1. 数据源 : DriverManagerDataSource --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/sandui?characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="123456" /> <!-- 从池中获取连接前进行验证 --> <property name="testOnBorrow" value="false" /> <!-- 向池中还回连接前进行验证 --> <property name="testOnReturn" value="false" /> <!-- 连接空闲时验证 --> <property name="testWhileIdle" value="true" /> <!-- 运行判断连接超时任务(evictor)的时间间隔,单位为毫秒,默认为-1,即不执行任务。 --> <property name="timeBetweenEvictionRunsMillis" value="300000" /> <!-- 连接的超时时间,默认为半小时。 --> <property name="minEvictableIdleTimeMillis" value="1800000" /> <!-- 每次evictor启动检查的空闲连接数,-2标识1/2的总空闲连接 --> <property name="numTestsPerEvictionRun" value="-1"></property> <!-- 线程池初始数量 --> <property name="initialSize" value="10"></property> <!-- 最大线程数量 --> <property name="maxActive" value="50"></property> <!-- 最大空闲线程数量 --> <property name="maxIdle" value="20"></property> <!-- 最小空闲线程数量 --> <property name="minIdle" value="10"></property> <!-- 从线程池获取一个mysql连接的最大等待时间,单位毫秒 --> <property name="maxWait" value="1000"></property> </bean> <!-- 2. mybatis的SqlSession的工厂--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 所有配置的mybatis映射文件 --> <property name="mapperLocations" value="classpath:com/maven/web/mapping/*.xml" /> </bean> <!-- 3. mybatis自动扫描加载Sql接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.maven.web.mapper"></property> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> <!-- 4. 事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
五, Spring-servlet.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: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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.maven.web.controller" /> <mvc:annotation-driven> <mvc:message-converters> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <description>JSON转换器</description> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 定义ViewResolver组件, 实现根据视图标识获取JSP响应 --> <mvc:view-resolvers> <mvc:jsp cache-views="false" prefix="/WEB-INF/html/" suffix=".jsp" /> </mvc:view-resolvers> <!-- 静态资源访问,不被DispatcherServlet处理 --> <mvc:resources mapping="jsp/**" location="/WEB-INF/jsp/" /> <mvc:resources mapping="/js/**" location="/js/" /> <!-- 开启默认处理 --> <mvc:default-servlet-handler /> </beans>
六,mybatis 自动生成代码工具
(1) 引入jar包
(2) 加入配置文件,mbgConfiguration.xml ,主要是对数据库的连接配置,代码生成后的存放目录配置,以及需要生成代码的数据库对应表的配置
(3) 编写java类,加载配置文件,生成代码
七,mbgConfiguration.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> <!-- 配置mysql 驱动jar包路径.用了绝对路径 --> <classPathEntry location="D:/java/mvnRespo/org/mybatis/mybatis/3.3.0/mybatis-3.3.0.jar" /> <context id="mysql_tables " targetRuntime="MyBatis3"> <!-- 为了防止生成的代码中有很多注释,比较难看,加入下面的配置控制 --> <commentGenerator> <property name="suppressAllComments" value="true" /> <property name="suppressDate" value="true" /> </commentGenerator> <!-- 注释控制完毕 --> <!-- 数据库连接 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/sandui?characterEncoding=utf8" userId="root" password="123456"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 数据表对应的model 层 --> <javaModelGenerator targetPackage="com.maven.web.entity" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- sql mapper 隐射配置文件 --> <sqlMapGenerator targetPackage="com.maven.web.mapping" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 在ibatis2 中是dao层,但在mybatis3中,其实就是mapper接口 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.maven.web.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 要对那些数据表进行生成操作,必须要有一个. --> <table schema="mybatis" tableName="cargoinfo" domainObjectName="CargoInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration>
八,在main函数中加载配置文件,启动生成代码,源码如下:
package com.maven.web.util; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.exception.InvalidConfigurationException; import org.mybatis.generator.exception.XMLParserException; import org.mybatis.generator.internal.DefaultShellCallback; public class GenMain { public static void main(String[] args) { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; String genCfg = "/mbgConfiguration.xml"; File configFile = new File(GenMain.class.getResource(genCfg).getFile()); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = null; try { config = cp.parseConfiguration(configFile); } catch (IOException e) { e.printStackTrace(); } catch (XMLParserException e) { e.printStackTrace(); } DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = null; try { myBatisGenerator = new MyBatisGenerator(config, callback, warnings); } catch (InvalidConfigurationException e) { e.printStackTrace(); } try { myBatisGenerator.generate(null); } catch (SQLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
运行后,刷新工程,就可以看到配置的目录下面已经自动生成好了代码,目录如下:
九,新建controller,service 完成简单的增删查操作.