springmvc配置mybatis与hibernate的不同点,springmvcmybatis

springmvc配置mybatis与hibernate的不一致点,springmvcmybatis

信赖各种人对springmvc+hibernate可能springmvc+mybatis都不会目生,拿来八个项目也都会付出。可是自个儿布置的动静下却相当少,就算本人配置过,长日子不写也会忘,在这里记录一下配置的进程以及遇到的主题材料。以maven项目为例,首先是springmvc+hibernate的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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>maven-springmvc</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>maven-springmvc Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <!--项目依赖 -->
  <dependencies>

    <!-- 添加Hibernate依赖 -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.8.Final</version>
    </dependency>
    <!-- dbcp连接池需要的jar包 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <!--日志包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.21</version>
    </dependency>
    <dependency>
      <groupId>org.javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.19.0-GA</version>
    </dependency>

    <!--j2ee相关包 servlet、jsp、jstl-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>


    <!-- 添加oracle jdbc driver -->
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.1.0</version>
    </dependency>



    <!--spring相关包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <!--jackson-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.7.0</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <!--其他需要的包-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.4</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>maven-springmvc</finalName>
    <resources>
      <!--表示把java目录下的有关xml文件,properties文件编译/打包的时候放在resource目录下-->
      <resource>
        <directory>${basedir}/src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>${basedir}/src/main/resources</directory>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <configuration>
          <url>http://localhost:8080/manager/text</url>
          <server>tomcat7</server>
          <username>tomcat</username>
          <password>tomcat</password>
          <path>/maven-springmvc</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

根本的重视性包蕴日志包(log4j),oracle驱动包,spring及springmvc的依赖包,jackson依赖包(转化json),maven的tomcat插件,数据库连接池数据源的jar包(dbcp),文件上传需求的包,以及hibernate的包。那个大旨就足以满意springmvc+hibernate的主导必要了。再来看看springmvc+mybatis的配备:

<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>
  <groupId>com.example</groupId>
  <artifactId>maven-springmvc</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>maven-springmvc Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <!--项目依赖 -->
  <dependencies>

    <!-- mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.5</version>
    </dependency>
    <!--整合spring mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
    <!-- dbcp连接池需要的jar包 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <!--日志包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.21</version>
    </dependency>
    <dependency>
      <groupId>org.javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.19.0-GA</version>
    </dependency>

    <!--j2ee相关包 servlet、jsp、jstl-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>


    <!-- 添加oracle jdbc driver -->
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.1.0</version>
    </dependency>



    <!--spring相关包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <!--jackson-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.7.0</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <!--其他需要的包-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.4</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>maven-springmvc</finalName>
    <resources>
      <!--表示把java目录下的有关xml文件,properties文件编译/打包的时候放在resource目录下-->
      <resource>
        <directory>${basedir}/src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>${basedir}/src/main/resources</directory>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <configuration>
          <url>http://localhost:8080/manager/text</url>
          <server>tomcat7</server>
          <username>tomcat</username>
          <password>tomcat</password>
          <path>/maven-springmvc</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

相比较五个布局文件,除了mybatis的maven正视以外,其余的都是一致的(废话)。这里正是小心一下除了mybatis的信赖,还应该有mybatis整合spring的借助,若是您也用的是spring+mybatis的话,就须要了。

下一场正是spring的布署文件了,大家驾驭springmvc须求四个布局文件,首先我们要在web.xml中布局

<!--配置springmvc DispatcherServlet-->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!--Sources标注的文件夹下需要新建一个spring文件夹-->
      <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>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

报告项目我们要用springmvc,将富有央浼提交DispatcherServlet再转给springmvc的调控器(controller),接下去便是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-3.2.xsd
                         http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.2.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--启用spring的一些annotation -->
    <context:annotation-config/>

    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <!--<context:component-scan base-package="com.example.controller">-->
        <!--<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
    <!--</context:component-scan>-->
    <context:component-scan base-package="com.example.controller"/>

    <!--HandlerMapping 无需配置,springmvc可以默认启动-->

    <!--静态资源映射-->
    <!--本项目把静态资源放在了WEB-INF的statics目录下,资源映射如下-->
    <mvc:resources mapping="/css/**" location="/WEB-INF/statics/css/"/>
    <mvc:resources mapping="/js/**" location="/WEB-INF/statics/js/"/>
    <mvc:resources mapping="/image/**" location="/WEB-INF/statics/image/"/>

    <!--但是项目部署到linux下发现WEB-INF的静态资源会出现无法解析的情况,但是本地tomcat访问正常,因此建议还是直接把静态资源放在webapp的statics下,映射配置如下-->
    <!--<mvc:resources mapping="/css/**" location="/statics/css/"/>-->
    <!--<mvc:resources mapping="/js/**" location="/statics/js/"/>-->
    <!--<mvc:resources mapping="/image/**" location="/statics/images/"/>-->

    <!-- 配置注解驱动 可以将request参数与绑定到controller参数上 -->

    <mvc:annotation-driven>
        <mvc:message-converters>
            <ref bean="stringHttpMessageConverter"/>
            <ref bean="mappingJackson2HttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <bean id="stringHttpMessageConverter"
          class="org.springframework.http.converter.StringHttpMessageConverter"/>

    <!--解决IE浏览器json文件下载和json数据中午乱码的问题-->
    <bean id="mappingJackson2HttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>



    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀(如果最后一个还是表示文件夹,则最后的斜杠不要漏了) 使用JSP-->
    <!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- -->
    <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/view/"/><!--设置JSP文件的目录位置-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- springmvc文件上传需要配置的节点-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="20971500"/>
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="resolveLazily" value="true"/>
    </bean>




</beans>

先是大家要布署controller的包,钦定哪个包下是调控器,<mvc:resources
是布局静态能源的最初,即安插访谈的目录是不通过DispatcherServlet调节器,那样我们就足以访问静态财富。然后就是安插jackson的转变器,使我们在@Responsebody时得以一贯回到json格式的多寡。<mvc:annotation-driven/>是注脚驱动运维,那样就能够由此表明分析调控器了,将写好的converter绑定到个中。然后正是布署视图解析器,钦点模板引擎寄存的路径以及后缀,最终布置一下spinrgmvc文件上传须求的安顿的节点。关于springmvc配置文件的配置,没什么不相同样的(无论是hibernate照旧mybatis)

下一场正是spring的配备了,常常情状下spring的配备蕴含3个部分:

二个是spring-bean,首若是安顿扫描包,首借使dao层,实现依据注入

其次个是spring-dao,配置数据连接相关安插,这里mybatis和hibernate有相当大区别了,

其八个是spring-service,主即使安顿部分政工逻辑管理(AOP),大家这里先不商讨。

本身那边web.xml的配置独有五个文本(其实假使写三个内部理论也是足以的),web.xml配置

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml,classpath:hibernateConfig.xml</param-value>
  </context-param>

ContextLoaderListener是spring的监听器,只要用到spring料定是索要的,器参数contextConfigLocation就是用来加载大家要求的布置文件,我这里独有七个,一个是用来围观bean的,多个是用来布局数据连接方面包车型客车,applicationContext.xml就也正是spring-bean,内容为;

<?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">

    <!-- 扫描文件(自动将servicec层注入) -->
    <context:component-scan base-package="com.example.dao"/>
</beans>

此处小编只安顿了扫描service包那句,指标是能够让service层能够注入。但在安插mybatis的时候出现了四个主题材料,之后再说

下一场正是hibernateConfig.xml,正是连接池以及hibernate的布局了

<?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"
       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/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
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    ">
    <!-- 读取hibernate.properties配置文件 -->
    <context:property-placeholder location="classpath:hibernate.properties" />

    <!-- 使用dbcp数据源,Oracle数据库 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="maxActive" value="30"></property>
        <property name="maxIdle" value="10"></property>
        <property name="maxWait" value="1000"></property>
        <property name="defaultAutoCommit" value="true"></property>
    </bean>

    <!-- session工厂 -->
    <!-- spring与hibernate整合配置,扫描所有dao -->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <!-- 是否根据需要每次自动创建数据库 -->
                <prop key="hibernate.hbm2ddl.auto">${jdbc.hbm2ddl.auto}</prop>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <!-- 显示Hibernate持久化操作所生成的SQL -->
                <prop key="hibernate.show_sql">${jdbc.show_sql}</prop>
                <prop key="hibernate.format_sql">${jdbc.format_sql}</prop>
            </props>
        </property>
        <!-- 扫描单个class-->
        <property name="annotatedClasses">
        <list>
            <value>com.example.pojo.Message</value>
        </list>
        </property>
        <!--&lt;!&ndash;扫描整个package,加载整个包下的class&ndash;&gt;-->
        <!--<property name="packagesToScan">-->
            <!--<list>-->
                <!--<value>com.example.pojo</value>-->
            <!--</list>-->
        <!--</property>-->
        <!--扫描一个配置文件-->
        <property name="mappingResources">
        <array>
            <value>com/example/dao/orm/Book.hbm.xml</value>
        </array>
        </property>
        <!--<property name="mappingDirectoryLocations">-->
            <!--<list>-->
                <!--<value>com/example/dao/orm</value>-->
            <!--</list>-->
        <!--</property>-->
    </bean>

   <!-- <bean id="bookDao" class="com.example.dao.impl.BookDaoImpl">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>-->

    <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!-- 对数据源进行事务管理 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

先是要加载一下hibernate的配置文件,hibernate.properties

#sqlserver
#jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
#jdbc.url=jdbc:sqlserver://192.168.1.60:1408;DatabaseName=test
#jdbc.username=sa
#jdbc.password=1111

#mysql
#jdbc.driverClassName=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost:3306/test
#jdbc.username=root
#jdbc.password=root

#Oracle
jdbc.dialect=org.hibernate.dialect.Oracle10gDialect
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@10.64.68.195:xxxx:orcl
jdbc.username=xxxxxx
jdbc.password=xxxxxx

jdbc.hbm2ddl.auto=update
jdbc.show_sql=true
jdbc.format_sql=true

接下来正是布置数据连接的连接源,我那边用的是dbcp(还可能有c3p0和proxool),然后就是布置hibernate的SessionFactory了,这里本身利用的是hibernate4,org.springframework.orm.hibernate4.LocalSessionFactoryBean,将数据源配置到sessionFactory中,<property
name=”annotatedClasses”>是将大家调换的实体类参加hibernate中,那样在选用hibernate的hql时,注明正是实体类的类名了,不然hibernate不会识别。使用hibernate的话,实体类能够依附数据库中的表生成实体类,也能够依据实体类生成表。

倘使用实体类生成表的话就须求在sessionFactory中到场<property
name=”mappingResources”>,即把映射文件参预进来,然后修改一下hibernate.hbm2ddl.auto的不二诀要,这里就十分的少做牵线了。

下一场正是附上一下本人的service文件:

package com.example.dao;

import com.example.pojo.Message;

import java.util.List;

public interface MessageDao {

    public Message findMessageById(String id);

    public void saveMessage(Message message);

    public List<Message> findMessageAll();

    public String getMessageName();
}

package com.example.dao.impl;

import com.example.dao.MessageDao;
import com.example.pojo.Message;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageDaoImpl implements  MessageDao {

    @Autowired
    private SessionFactory sessionFactory;

    //获取和当前线程绑定的Session
    private Session getSession(){
        return sessionFactory.openSession();
    }

    public Message findMessageById(String id) {
        //实例化Configuration,这行代码默认加载hibernate.cfg.xml文件
        //String hql = "FROM  Message where id = ?";
        String hql = "FROM  Message where id = ?";
        Query query = getSession().createQuery(hql).setString(0,id);
        Message message = (Message) query.uniqueResult();
        return message;
    }
    public void saveMessage(Message message) {
        getSession().save(message);
    }

    public List<Message> findMessageAll() {
        String hql = " FROM  Message";
        Query query = getSession().createQuery(hql);
        List<Message> messageList = query.list();
        return messageList;
    }

    public String getMessageName() {
        String name = "测试消息";
        return name;
    }
}

能够见见在笔者在接口的兑现类中通过注入的办法注入了Hibernate的sessionFactory,这里须求潜心一下,要是这里运用注入的主意,那么在使用那一个service的兑现类时,也必须求运用注入的章程引入那么些类,不然sessionFactory会是null。再然后需求专一的正是收获session的措施,笔者这里运用的是sessionFactory.openSession()的艺术,小编看网络给的好种种都是sessionFactory.getCurrentSession()那一个艺术,可是假若你采纳的是hibernate4的话,getCurrentSession()那个情势就随意用了,注意一下。然后大家就能够通过hibernate的session实行数据库操作了。到此springmvc+hibernate的铺排就到此甘休了,接下去大家说一下springmvc+mybatis的布署,由于时代久远都不行了,在此以前用过亦不是springmvc一同用的,所以陈设的时候还是忘了无数。

此处最亟需注意的便是mybatis是内需mapper类的,mapper类对应的就是mybatis的sql
xml中的方法,有了mapper类大家才具调用mybatis写好的sql方法
此处我们看一下web.xml中的配置

 

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springbeans.xml,classpath:mybatis.xml</param-value>
  </context-param>

 

安插文件只怕八个,多少个bean四个dao,名字不平等而已,大家看一下mybatis.xml

图片 1

先截一下体系目录的图,方便之后表达。

<?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:mybatis="http://mybatis.org/schema/mybatis-spring"
       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://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 该包下的类支持注解,表示会被当作{@code mybatis mapper}处理 配置了之后表示可以自动引入mapper类-->
    <mybatis:scan base-package="com.mvc.dao"/>

    <!-- 自动扫描注解的bean -->
    <context:component-scan base-package="com.mvc.dao" />

    <!--引入属性文件 -->
    <context:property-placeholder location="classpath:mybatis.properties"/>
    <!--数据库连接-->
    <bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <!--链接池中最大连接数,默认为8-->
        <property name="maxActive" value="30"></property>
        <!--链接池中最大空闲连接数,默认为8-->
        <property name="maxIdle" value="10"></property>
        <!--链接池中最小空闲连接数,默认为0-->
        <property name="minIdle" value="0"></property>
        <!--当连接池资源耗尽时,调用者最大阻塞的时间,超时将跑出异常。单位,毫秒数;默认为-1.表示永不超时-->
        <property name="maxWait" value="1000"></property>
        <property name="defaultAutoCommit" value="true"></property>

    </bean>
    <!-- mybatis配置 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"/>
        <!-- 加载Mybatis全局配置文件 -->
        <property name="configLocation" value="classpath:mapper/SqlMapConfig.xml"/>
    </bean>

    <!-- 配置mapper扫描器 -->
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描包路径,如果需要扫描多个包中间用半角逗号隔开 -->
        <property name="basePackage" value="com.mvc.dao"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
</beans>

<!-- 该包下的类支持注解,表示会被当作{@code mybatis mapper}处理 配置了之后表示可以自动引入mapper类-->
    <mybatis:scan base-package="com.mvc.dao"/>

    <!-- 自动扫描注解的bean -->
    <context:component-scan base-package="com.mvc.dao" />

这两句小编不晓得有何样不一样,目标都以一样,能够注入dao层的类,这里的dao层就是mybatis的mapper层,自动注入方便我们在service中注入mapper。然后是布署mybatis的sqlSessionFactory,对应的类是org.mybatis.spring.SqlSessionFactoryBean,类似hibernate的sessionFactory,将数据源配置进来,然后正是再把mybatis的mapper配置文件加载进来,SqlMapConfig.xml,也叫全局配置文件,<property
name=”configLocation” value=”classpath:mapper/SqlMapConfig.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>

    <!-- 将数据库连接数据抽取到属性文件中方便测试 -->
    <!-- <properties resource="/WEB-INF/classes/jdbc.properties"></properties> -->
    <!-- 别名的定义 -->
    <!--<typeAliases>-->
        <!--<typeAlias alias="User" type="cn.jxufe.web.mybatis.User"/>-->
    <!--</typeAliases>-->
    <typeAliases>
        <typeAlias alias="Book" type="com.mvc.pojo.Book"/>
    </typeAliases>

    <!-- 数据库连接用数据库连接池 -->

    <mappers>
        <!-- 加载映射文件 -->
        <!-- 这里也可以使用class来加载映射文件,前提是:使用mapper代理的方法,遵循规范,
        并且两个文件必须同名且在同一目录
        <mapper class="com.wxisme.mybatis0100.mapper.UserMapper"/>
        基于class加载,可以进行批量加载
        -->
        <!-- 通过扫描包的方式来进行批量加载映射文件 -->
        <!--<package name="com.wxisme.ssm.mapper"/>-->
        <mapper resource="mapper/BookMapper.xml"/>

    </mappers>
</configuration>

那其间根本三个标签,贰个是<type阿里ases>,这一个标签的效率正是布署实体类小名,那样的话大家在xxMapper.xml中得以应用类的小名,可以单个类加载,也能够整个包加载,别的一个是<mappers>,正是加载大家的投射文件了,这里自身写了叁个BookMapper.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.mvc.dao.BookMapper">
    <insert id="insertBook" parameterType="Book">
        insert into book values( #{id}, #{bookName}, #{isbn}, #{price}, #{stock})
    </insert>
    <!--  查询单条记录  -->
    <select id="getBookById" parameterType="int" resultType="Book">
        select * from book where id = #{id}
    </select>
</mapper>

这里大家看一下,<mapper>标签下
namespace正是对应的mapper类,mapper类中写的章程正是大家映射文件的措施(名称要一致),这里的parameterType就是参数类型了,这里本人就用到了前头在安插文件中布局的外号了,resultType就是回到类型了,小心若无别的配置,这里的Book里的性质,要和book表中字段完全一样才行。也得以手动配置。

然后大家再回去看一下mybatis.xml中的配置,配置完sqlSessionFactory后,要求加一个mapper扫描器,这里hibernate是从未有过的,也是mybatis独有的,因为mybatis才有mapper

<!-- 配置mapper扫描器 -->
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描包路径,如果需要扫描多个包中间用半角逗号隔开 -->
        <property name="basePackage" value="com.mvc.dao"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

此间又扫描了二次mapper包,然后将sqlSessionFactory配置进来,笔者以为mapper扫描器是一定要用的,但配备那块还供给具体商讨一下。先记录下来。那样安插就基本竣事了。

然后大家看一下调用,mybatis大家得以一直调用mapper类中的方法,至于何以不像Hibernate这样须要session,是接下去必要上学的

public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    public Book getBook(int id) {
        return bookMapper.getBookById(id);
    }

    public void insertBook(Book book) {
        bookMapper.insertBook(book);
    }
}

这边一向注意bookMapper,bookMapper的艺术正是bookMapper.xml中定义的。然后大家在controller中流入BookServiceImpl就行了。

这边就应时而生了一个难点,这里本身附上自身mybatis项目中springbeans.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.mvc.service"/>
    <bean id ="userService" class="com.mvc.service.impl.BookServiceImpl"/>


</beans>

自己想像此前hibernate项目中时一直用扫描包的措施注入BookServiceImpl时,退步了,那地方还不领悟原因,也是先记下一下。恐怕手动的布置一下那一个类,才注入成功的。我们写的时候也是,若是乐此不疲,能够三个类二个类手动注入,类似<bean
id =”userService”
class=”com.mvc.service.impl.BookServiceImpl”/>这种。注入时名字就为userService。

最后总计一下hibernate和mybatis配置相同和不一致的多少个地点。

同样点:1,都亟待配备数据源(dbcp,c3p0,proxool)

    2,都亟待个.properties文件,用来保存数据库相关属性(举例是如何数据库,客商名,密码之类的),也得以利用xml文件(hibernate能够,mybatis不太掌握不敢说)

    3,都急需配置sessionFactory,hibernate叫sessionFactory,mybatis叫sqlSessionFactory。

不相同点:1,mybatis是内需mapper层的,mapper层对应mapper的照耀文件。

    2,在mybatis的sqlSessionFactory,必要将mybatis的全局配置文件参预,全局配置文件中布局实体类的别称typeAliases和照耀文件mappers。

    3,mybatis供给配备mapper扫描器,扫描器将围观mapper包,然后把sqlSessionFactory配置进来。

    4,达成查询的话,hibernate是应用sessionFactory创设的session进行操作,无需手动写sql。而mybatis则是写好各个xxMapper.xml然后再写对应的mapper类,然后每回调用的时候利用mapper类中的方法完成数据库的操作。

 

以上是自己个人以三个初大方的角度张开的下结论,逻辑亦不是很鲜明,学术性更不用说了,只当作是给协和随后忘了的时候看的。现在有上学到新的事物还亟需做过多补偿。在此间先作为记录。

 

 

相信各类人对springmvc+hibernate可能springmvc+mybatis都不会面生,拿来二个门类也都会支付。但…

深信不疑各个人对springmvc+hibernate只怕springmvc+mybatis都不会不熟悉,拿来三个类型也都会开垦。不过自身配置的情景下却少之甚少,即便本人安顿过,长日子不写也会忘,在此处记录一下安插的长河以及遭逢的标题。以maven项目为例,首先是springmvc+hibernate的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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>maven-springmvc</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>maven-springmvc Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <!--项目依赖 -->
  <dependencies>

    <!-- 添加Hibernate依赖 -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.8.Final</version>
    </dependency>
    <!-- dbcp连接池需要的jar包 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <!--日志包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.21</version>
    </dependency>
    <dependency>
      <groupId>org.javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.19.0-GA</version>
    </dependency>

    <!--j2ee相关包 servlet、jsp、jstl-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>


    <!-- 添加oracle jdbc driver -->
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.1.0</version>
    </dependency>



    <!--spring相关包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <!--jackson-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.7.0</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <!--其他需要的包-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.4</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>maven-springmvc</finalName>
    <resources>
      <!--表示把java目录下的有关xml文件,properties文件编译/打包的时候放在resource目录下-->
      <resource>
        <directory>${basedir}/src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>${basedir}/src/main/resources</directory>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <configuration>
          <url>http://localhost:8080/manager/text</url>
          <server>tomcat7</server>
          <username>tomcat</username>
          <password>tomcat</password>
          <path>/maven-springmvc</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

要害的信赖包蕴日志包(log4j),oracle驱动包,spring及springmvc的正视性包,jackson信任包(转化json),maven的tomcat插件,数据库连接池数据源的jar包(dbcp),文件上传须求的包,以及hibernate的包。这么些骨干就足以满意springmvc+hibernate的主导要求了。再来看看springmvc+mybatis的计划:

<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>
  <groupId>com.example</groupId>
  <artifactId>maven-springmvc</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>maven-springmvc Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <!--项目依赖 -->
  <dependencies>

    <!-- mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.5</version>
    </dependency>
    <!--整合spring mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
    <!-- dbcp连接池需要的jar包 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <!--日志包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.21</version>
    </dependency>
    <dependency>
      <groupId>org.javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.19.0-GA</version>
    </dependency>

    <!--j2ee相关包 servlet、jsp、jstl-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>


    <!-- 添加oracle jdbc driver -->
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.1.0</version>
    </dependency>



    <!--spring相关包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <!--jackson-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.7.0</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <!--其他需要的包-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.4</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>maven-springmvc</finalName>
    <resources>
      <!--表示把java目录下的有关xml文件,properties文件编译/打包的时候放在resource目录下-->
      <resource>
        <directory>${basedir}/src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>${basedir}/src/main/resources</directory>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <configuration>
          <url>http://localhost:8080/manager/text</url>
          <server>tomcat7</server>
          <username>tomcat</username>
          <password>tomcat</password>
          <path>/maven-springmvc</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

对待多个布局文件,除了mybatis的maven信赖以外,别的的没什么区别样的(废话)。这里正是注意一下除了mybatis的信赖,还大概有mybatis整合spring的信赖,如若你也用的是spring+mybatis的话,就供给了。

然后正是spring的安插文件了,大家领会springmvc须求一个计划文件,首先大家要在web.xml中布局

<!--配置springmvc DispatcherServlet-->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!--Sources标注的文件夹下需要新建一个spring文件夹-->
      <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>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

报告项目大家要用springmvc,将兼具央浼提交DispatcherServlet再转给springmvc的调节器(controller),接下去正是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-3.2.xsd
                         http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.2.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--启用spring的一些annotation -->
    <context:annotation-config/>

    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <!--<context:component-scan base-package="com.example.controller">-->
        <!--<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
    <!--</context:component-scan>-->
    <context:component-scan base-package="com.example.controller"/>

    <!--HandlerMapping 无需配置,springmvc可以默认启动-->

    <!--静态资源映射-->
    <!--本项目把静态资源放在了WEB-INF的statics目录下,资源映射如下-->
    <mvc:resources mapping="/css/**" location="/WEB-INF/statics/css/"/>
    <mvc:resources mapping="/js/**" location="/WEB-INF/statics/js/"/>
    <mvc:resources mapping="/image/**" location="/WEB-INF/statics/image/"/>

    <!--但是项目部署到linux下发现WEB-INF的静态资源会出现无法解析的情况,但是本地tomcat访问正常,因此建议还是直接把静态资源放在webapp的statics下,映射配置如下-->
    <!--<mvc:resources mapping="/css/**" location="/statics/css/"/>-->
    <!--<mvc:resources mapping="/js/**" location="/statics/js/"/>-->
    <!--<mvc:resources mapping="/image/**" location="/statics"/>-->

    <!-- 配置注解驱动 可以将request参数与绑定到controller参数上 -->

    <mvc:annotation-driven>
        <mvc:message-converters>
            <ref bean="stringHttpMessageConverter"/>
            <ref bean="mappingJackson2HttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <bean id="stringHttpMessageConverter"
          class="org.springframework.http.converter.StringHttpMessageConverter"/>

    <!--解决IE浏览器json文件下载和json数据中午乱码的问题-->
    <bean id="mappingJackson2HttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>



    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀(如果最后一个还是表示文件夹,则最后的斜杠不要漏了) 使用JSP-->
    <!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- -->
    <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/view/"/><!--设置JSP文件的目录位置-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- springmvc文件上传需要配置的节点-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="20971500"/>
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="resolveLazily" value="true"/>
    </bean>




</beans>

先是大家要安排controller的包,钦点哪个包下是调节器,<mvc:resources
是布局静态财富的初叶,即布置访谈的目录是不通过DispatcherServlet调整器,这样我们就足以访问静态能源。然后就是安插jackson的调换器,使我们在@Responsebody时可以直接回到json格式的多寡。<mvc:annotation-driven/>是评释驱动运行,这样就可以透过申明解析调节器了,将写好的converter绑定到个中。然后正是安插视图解析器,内定模板引擎贮存的路径以及后缀,最后安顿一下spinrgmvc文件上传须要的安插的节点。关于springmvc配置文件的配置,没什么分化样的(无论是hibernate依旧mybatis)

下一场正是spring的配置了,常常情状下spring的配备包蕴3个部分:

多个是spring-bean,首假设布置扫描包,首如若dao层,完成依据注入

第三个是spring-dao,配置数据连接相关配置,这里mybatis和hibernate有十分大不一样了,

其八个是spring-service,首要是安顿部分政工逻辑处理(AOP),我们这里先不研讨。

自个儿那边web.xml的配备独有七个文本(其实假如写两个之中理论也是足以的),web.xml配置

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml,classpath:hibernateConfig.xml</param-value>
  </context-param>

ContextLoaderListener是spring的监听器,只要用到spring明确是急需的,器参数contextConfigLocation就是用来加载我们供给的安排文件,我这里唯有五个,叁个是用来围观bean的,二个是用来配置数据连接方面包车型地铁,applicationContext.xml就一定于spring-bean,内容为;

<?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">

    <!-- 扫描文件(自动将servicec层注入) -->
    <context:component-scan base-package="com.example.dao"/>
</beans>

那边笔者只布置了围观service包那句,目标是能够让service层能够注入。但在配置mybatis的时候出现了二个主题素材,之后再说

下一场正是hibernateConfig.xml,就是连接池以及hibernate的布局了

<?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"
       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/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
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    ">
    <!-- 读取hibernate.properties配置文件 -->
    <context:property-placeholder location="classpath:hibernate.properties" />

    <!-- 使用dbcp数据源,Oracle数据库 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="maxActive" value="30"></property>
        <property name="maxIdle" value="10"></property>
        <property name="maxWait" value="1000"></property>
        <property name="defaultAutoCommit" value="true"></property>
    </bean>

    <!-- session工厂 -->
    <!-- spring与hibernate整合配置,扫描所有dao -->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <!-- 是否根据需要每次自动创建数据库 -->
                <prop key="hibernate.hbm2ddl.auto">${jdbc.hbm2ddl.auto}</prop>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <!-- 显示Hibernate持久化操作所生成的SQL -->
                <prop key="hibernate.show_sql">${jdbc.show_sql}</prop>
                <prop key="hibernate.format_sql">${jdbc.format_sql}</prop>
            </props>
        </property>
        <!-- 扫描单个class-->
        <property name="annotatedClasses">
        <list>
            <value>com.example.pojo.Message</value>
        </list>
        </property>
        <!--&lt;!&ndash;扫描整个package,加载整个包下的class&ndash;&gt;-->
        <!--<property name="packagesToScan">-->
            <!--<list>-->
                <!--<value>com.example.pojo</value>-->
            <!--</list>-->
        <!--</property>-->
        <!--扫描一个配置文件-->
        <property name="mappingResources">
        <array>
            <value>com/example/dao/orm/Book.hbm.xml</value>
        </array>
        </property>
        <!--<property name="mappingDirectoryLocations">-->
            <!--<list>-->
                <!--<value>com/example/dao/orm</value>-->
            <!--</list>-->
        <!--</property>-->
    </bean>

   <!-- <bean id="bookDao" class="com.example.dao.impl.BookDaoImpl">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>-->

    <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!-- 对数据源进行事务管理 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

先是要加载一下hibernate的配备文件,hibernate.properties

#sqlserver
#jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
#jdbc.url=jdbc:sqlserver://192.168.1.60:1408;DatabaseName=test
#jdbc.username=sa
#jdbc.password=1111

#mysql
#jdbc.driverClassName=com.mysql.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost:3306/test
#jdbc.username=root
#jdbc.password=root

#Oracle
jdbc.dialect=org.hibernate.dialect.Oracle10gDialect
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@10.64.68.195:xxxx:orcl
jdbc.username=xxxxxx
jdbc.password=xxxxxx

jdbc.hbm2ddl.auto=update
jdbc.show_sql=true
jdbc.format_sql=true

接下来正是计划数据连接的连接源,小编那边用的是dbcp(还有c3p0和proxool),然后就是安顿hibernate的SessionFactory了,这里小编利用的是hibernate4,org.springframework.orm.hibernate4.LocalSessionFactoryBean,将数据源配置到sessionFactory中,<property
name=”annotatedClasses”>是将大家转移的实体类插足hibernate中,那样在选择hibernate的hql时,注解正是实体类的类名了,不然hibernate不会识别。使用hibernate的话,实体类可以依靠数据库中的表生成实体类,也能够依据实体类生成表。

借使用实体类生成表的话就要求在sessionFactory中步向<property name=”mappingResources”>,即把映射文件加入进去,然后修改一下hibernate.hbm2ddl.auto的秘技,这里就十分的少做牵线了。

然后就是附上一下自己的service文件:

package com.example.dao;

import com.example.pojo.Message;

import java.util.List;

public interface MessageDao {

    public Message findMessageById(String id);

    public void saveMessage(Message message);

    public List<Message> findMessageAll();

    public String getMessageName();
}

package com.example.dao.impl;

import com.example.dao.MessageDao;
import com.example.pojo.Message;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageDaoImpl implements  MessageDao {

    @Autowired
    private SessionFactory sessionFactory;

    //获取和当前线程绑定的Session
    private Session getSession(){
        return sessionFactory.openSession();
    }

    public Message findMessageById(String id) {
        //实例化Configuration,这行代码默认加载hibernate.cfg.xml文件
        //String hql = "FROM  Message where id = ?";
        String hql = "FROM  Message where id = ?";
        Query query = getSession().createQuery(hql).setString(0,id);
        Message message = (Message) query.uniqueResult();
        return message;
    }
    public void saveMessage(Message message) {
        getSession().save(message);
    }

    public List<Message> findMessageAll() {
        String hql = " FROM  Message";
        Query query = getSession().createQuery(hql);
        List<Message> messageList = query.list();
        return messageList;
    }

    public String getMessageName() {
        String name = "测试消息";
        return name;
    }
}

可以观察在自家在接口的落实类中经过注入的情势注入了Hibernate的sessionFactory,这里必要在意一下,假使这里运用注入的法子,那么在利用这一个service的落到实处类时,也不可能不要选用注入的点子引进那么些类,不然sessionFactory会是null。再然后需要留意的正是获得session的主意,笔者这边运用的是sessionFactory.openSession()的诀要,作者看网络给的繁多样都以sessionFactory.getCurrentSession()这一个方式,可是一旦你利用的是hibernate4的话,getCurrentSession()这一个法子就随意用了,注意一下。然后大家就可以透过hibernate的session实行数据库操作了。到此springmvc+hibernate的布局就到此甘休了,接下去我们说一下springmvc+mybatis的计划,由于绵绵都行不通了,此前用过亦不是springmvc一齐用的,所以计划的时候依旧忘了广大。

此地最须要小心的正是mybatis是急需mapper类的,mapper类对应的正是mybatis的sql
xml中的方法,有了mapper类大家本领调用mybatis写好的sql方法
此间大家看一下web.xml中的配置

 

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springbeans.xml,classpath:mybatis.xml</param-value>
  </context-param>

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注