关于java:两大热门框架-Spring-与-Mybatis-如何整合呢

36次阅读

共计 6899 个字符,预计需要花费 18 分钟才能阅读完成。

整合的形式

  • 新建 maven 我的项目
  • 引入依赖包
  • 配置资源文件

案例实操

新建 maven 我的项目

新建 maven 我的项目 spring_mybatis

目录构造如下:

主目录包:

​ com.xxx.dao、

​ com.xxx.mapper、

​ com.xxx.service、

​ com.xxx.service.impl

测试包:spring_mybatis

引入依赖包

关上 pom.xml 开始增加依赖包

<?xml version="1.0" encoding="UTF-8"?>

<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>com.xxx</groupId>
  <artifactId>test-xxxms</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>test-xxxms</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- spring 外围 jar -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- spring 测试 jar -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- spring jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- spring 事物 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>

    <!-- c3p0 连接池 -->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>

    <!-- mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
    </dependency>

    <!-- 增加 mybatis 与 Spring 整合的外围包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <!-- mysql 驱动包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.39</version>
    </dependency>

    <!-- 日志打印相干的 jar -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.2</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.2</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>tpl-web</finalName>

    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.xml</include>
          <include>**/*.properties</include>
        </includes>
      </resource>
    </resources>
  </build>
</project> 

配置资源文件

​ a) Spring 文件 spring.xml

​ b) Mybatis 文件 mybatis.xml

​ c) 数据库连贯 properties 文件 db.properties

​ d) 日志输入文件 log4j.properties

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:tx="http://www.springframework.org/schema/tx"
       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
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:component-scan base-package="com.xxx"/>

    <context:property-placeholder location="db.properties"/>

    <tx:annotation-driven  transaction-manager="txManager"/>

    <!-- 配置 c3p0 数据源  -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <bean id="txManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

<!--  整合 框架(Spring 与 Mybatis)-->

    <!-- 配置 sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 框架的配置文件 -->
        <property name="configLocation" value="classpath:mybatis.xml" />
        <!-- 映射文件 -->
        <property name="mapperLocations" value="classpath:com/xxx/dao/mapper/*.xml" />
    </bean>

    <!-- 配置扫描器 -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描 com.xxx.dao 这个包以及它的子包下的所有映射接口类 -->
        <property name="basePackage" value="com.xxx.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

</beans> 

mybatis.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>

    <!-- 别名的配置  每个人必须会 -->
    <typeAliases>
        <package name="com.xxx.model"/>
    </typeAliases>

</configuration> 

db.properties 文件配置(对于其它数据源属性配置,见 c3p0 配置解说,这里采纳默认属性配置)

建设数据库 mybatis(留神数据库,用户名,明码以本人本地数据库为准

jdbc.driver=com.mysql.jdbc.Driver 

jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding= 

utf8 

jdbc.username=root 

jdbc.password= 

log4j.properties

便于控制台日志输入

# Global logging configuration 
log4j.rootLogger=DEBUG, stdout 
# Console output... 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n 

扩大

开始编写 helloworld

User 实体类定义

public class User { 

    private int id; 

    private String userName; 

    private String userPwd; 

    public int getId() {return id;} 

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

    public String getUserName() {return userName;} 

    public void setUserName(String userName) {this.userName = userName;} 

    public String getUserPwd() {return userPwd;} 

    public void setUserPwd(String userPwd) {this.userPwd = userPwd;} 

    @Override 

    public String toString() { 

        return "User [id=" + id + ", userName=" + userName + ", userPwd=" 

    + userPwd + "]"; 

    } 

} 

UseDao 接口与映射文件定义

UserDao 接口

public interface UserDao {public User queryUserById(int id); 

} 

UserMapper.xml(留神:此时映射文件命名空间定义要合乎规定:接口包名 . 接口类

, 否则不按规定出牌,测试会报错,而后你就蒙圈了!!!)

<?xml version="1.0" encoding="UTF-8" ?> 

<!DOCTYPE mapper 

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 

"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 

<mapper namespace="com.xxx.dao.UserDao"> 

<select id="queryUserById" parameterType="int" resultType="user"> 

    select id,userName,userPwd from user where id=#{id}  

</select> 

</mapper> 

UserService 接口类与实现类定义

public interface UserService {public User queryUserById(); 

} 

UserServiceImpl 实现类 ( 此时间接注入咱们的 UserDao 接口即可,而后间接调用

其办法,事已至此,离胜利仅差一步!)

@Service 

public class UserServiceImpl implements UserService{ 

    @Resource 

    private UserDao userDao; 

    public User queryUserById(){return userDao.queryUserById(7);  

    } 

} 

junit 测试

因为与 spring 框架集成,咱们采纳 spring 框架测试 spring Test

@RunWith(SpringJUnit4ClassRunner.class) 

@ContextConfiguration(locations = {"classpath:spring.xml"} ) 

public class TestSpringMybatis { 

    @Autowired 

    private UserService userService; 

    @Test 

    public void testQueryUserById() {System.out.println(userService.queryUserById(1)); 

    } 

} 

正文完
 0