配置SpringMVC+Mybatis+SQLServer (1)

版权声明:本文为博主原创文章,转载请注明作者与出处,http://blog.csdn.net/lixingtao0520 https://blog.csdn.net/lixingtao0520/article/details/76598700

之前的文章中写到了怎么配置SpringMVC项目,下面在SpringMVC项目中配置MyBatis,数据库为SQLServer。


准备工作:

1、新建数据库mydb及数据表student

CREATE TABLE student(
       id int not null,
       student_name nvarchar(20) not null
)

INSERT INTO student (id,student_name)values(1,'张三')
INSERT INTO student (id,student_name)values(2,'李四')
INSERT INTO student (id,student_name)values(3,'王五')

开始配置SpringMVC+MyBatis+SQLServer
1 在tomcat文件下的context.xml文件中配置数据源

<Resource auth="Container"

     driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"

     logAbandoned="true"

     maxActive="100"

     maxIdle="20"

     maxWait="10000"
     name="jdbc/sqlServerMydb"

     password="123456"

     removeAbandoned="true"
     removeAbandonedTimeout="120"
     type="javax.sql.DataSource"
     url="jdbc:sqlserver://localhost:1433;DatabaseName=mydb"
     factory="org.apache.commons.dbcp.BasicDataSourceFactory"
     username="userName"/>
数据库用户名为username,密码为123456

2、pom.xml文件中引入myBatis,myBatis-spring,common-pool,commons-dbcp,spring-jdbc等依赖包

<dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-tx</artifactId>
       <version>${springVersion}</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-pool/commons-pool -->
     <dependency>
    <groupId>commons-pool</groupId>
    <artifactId>commons-pool</artifactId>
    <version>1.4</version>
     </dependency>
    <dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
    </dependency>
    <!-- spring-jdbc -->
    <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-jdbc</artifactId>
       <version>${springVersion}</version>
    </dependency>
    <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis</artifactId>
       <version>3.4.0</version>
     </dependency>
     <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis-spring</artifactId>
       <version>1.3.0</version>
     </dependency>

3、创建pojo类student,StudentDao,StudentService以及对应的student.xml文件。
Student.java
package com.xtli.pojo;

public class Student {
     private Integer id;

     private String name;

     public Integer getId() {
          return id;
     }

     public void setId(Integer id) {
          this.id = id;
     }

     public String getName() {
          return name;
     }

     public void setName(String name) {
          this.name = name;
     }
}
StudentDao.java
package com.xtli.dao;

import org.springframework.stereotype.Repository;

import com.xtli.pojo.Student;
/*
 * 测试MyBatisDao
 */
@Repository
public interface StudentDao {
     public Student getStudentById(Integer id);
}

StudentService.java
package com.xtli.service;

import com.xtli.pojo.Student;

public interface StudentService {
     public Student getStudentById(Integer id);
}

StudentServiceImpl.java
package com.xtli.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xtli.dao.StudentDao;
import com.xtli.pojo.Student;
import com.xtli.service.StudentService;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    @Override
    @Transactional(readOnly = false, rollbackFor = Throwable.class)
    public Student getStudentById(Integer id) {
        return studentDao.getStudentById(id);
    }
}


student.xml文件,此文件命名空间要与StudentDao路径保持一致
<?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.xtli.dao.StudentDao">
     <select id="getStudentById" parameterType="int" resultType="student">
          SELECT id,student_name AS name FROM student WHERE id=#{id}
     </select>
</mapper>

4、添加applicationContext.xml文件以及sqlMapConfig.xml文件

applicationContext.xml文件中主要是注入bean,配置数据源和sqlSessionFactory,sqlsessionTemplate。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"

    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/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
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
        >
   
    <!-- datasource define -->
     <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
          <property name="jndiName">
               <value>java:comp/env/jdbc/sqlServerMydb</value>
          </property>
     </bean>

     <!--MyBatis 的sqlSessionFactory -->
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
          <property name="dataSource" ref="dataSource" />
          <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
     </bean>

     <!-- sqlSessionTemplate -->
     <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
          <constructor-arg index="0" ref="sqlSessionFactory"/>
     </bean>

     <!-- 事务管理(Spring事务会覆盖JDBC事务) -->
    <!-- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <property name="dataSource" ref="dataSource"/>
     </bean> -->

     <!-- 使用注解管理事务 -->
     <!-- <tx:annotation-driven transaction-manager="transactionManager"  proxy-target-class="true"/> -->

     <!-- 采用自动扫描方式创建mapper bean -->
     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
          <property name="basePackage" value="com"/>
          <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
          <property name="annotationClass" value="org.springframework.stereotype.Repository"/>
     </bean>

</beans>

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>

     <settings>
          <!-- 这个配置使全局的映射器启用或禁用缓存 -->
          <setting name="cacheEnabled" value="true"/>
          <!-- 允许JDBC支持生成的键。需要适合的驱动。如果设置为true,则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如Derby) -->
          <setting name="useGeneratedKeys" value="true"/>
          <!-- 配置默认的执行器。SIMPLE执行器没有什么特别之处。REUSE执行器重用预处理语句。BATCH执行器重用语句和批量更新 -->
          <setting name="defaultExecutorType" value="REUSE"/>
          <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 -->
          <setting name="lazyLoadingEnabled" value="true"/>
          <!-- 设置超时时间,它决定驱动等待一个数据库响应的时间 -->
          <setting name="defaultStatementTimeout" value="25000"/>
     </settings>

     <!-- 自定义别名 -->
     <typeAliases>
          <!-- 单个别名定义 -->
          <typeAlias type="com.xtli.pojo.Student" alias="student"/>

          <!-- 批量别名定义(推荐) -->
          <!-- package:指定包名称来为该包下的po类声明别名,默认的别名就是类名(首字母大小写都可) -->
          <!-- <package name="com.xtli.pojo" /> -->
     </typeAliases>

     <!-- 指定映射器路径 -->
     <mappers>
          <mapper resource="com\xtli\dao\student.xml" />
          <!-- 批量加载映射文件 -->
          <!-- <package name="com.xtli.dao" /> -->
     </mappers>
</configuration>

5、创建StudentController

StudentController.java

package com.xtli.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.xtli.pojo.Student;
import com.xtli.service.StudentService;

@Controller
@RequestMapping(value="/studentController")
public class StudentController {
     private static final String STUDENT = "/xtli/student/studentList.jsp";

     @Autowired
     private StudentService studentService;

     /**
      * 测试MyBatis
      */
     @RequestMapping(value="/getStudent") 
     public ModelAndView getStudent(HttpServletRequest request) {
         ModelAndView mv = new ModelAndView(STUDENT);
         Integer id = 1;
         Student student = studentService.getStudentById(id);
        return mv.addObject("student", student);
     } 
}

创建studentList.jsp展示数据。

最终目录结构如下:


6、以上完成后,如果此时将项目放在Tomcat下,启动时,会报如下错误
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xtli.dao.StudentDao com.xtli.service.Impl.StudentServiceImpl.studentDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xtli.dao.StudentDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
     at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
     at 
     ...
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xtli.dao.StudentDao com.xtli.service.Impl.StudentServiceImpl.studentDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xtli.dao.StudentDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
     at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:517)
     at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
     at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
     ... 
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xtli.dao.StudentDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
     at 
     ...

这是因为我们配置的applicationContext.xml文件未在web.xml文件中配置,所配置的bean没有注入到Spring容器中,在web.xml中增加以下配置

    <!-- 配置ContextLoaderListener -->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:/applicationContext.xml</param-value>
    </context-param>
    <!-- 配置ContextLoaderListener -->
    <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>
ContextLoaderListener监听器,启动容器时,默认执行其中的 contextInitialize方法,此方法自动装配applicationContext.xml的配置,初始化webApplicationContext。源码如下

     public void contextInitialized(ServletContextEvent event) {
          this.contextLoader = createContextLoader();
          if (this.contextLoader == null) {
              this.contextLoader = this;
          }
          this.contextLoader.initWebApplicationContext(event.getServletContext());
     }

7、再次启动Tomcat,并输入URL,出现以下结果



配置完成。


猜你喜欢

转载自blog.csdn.net/lixingtao0520/article/details/76598700