Spring Mybatis Maven 一步步整合

前提: 设定项目为maven项目

步骤【1】: 添加jar包依赖

        <!--添加Spring相关的包-->
        <dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-jdbc</artifactId>
  		<version>4.2.3.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-context</artifactId>
  		<version>4.2.3.RELEASE</version>
  	</dependency>

        <!--添加Mybatis相关的包-->
        <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>
    
        <!--数据库连接池使用的是阿里的Druid-->
        <dependency>
  		<groupId>com.alibaba</groupId>
  		<artifactId>druid</artifactId>
  		<version>1.0.16</version>
  	</dependency>

        <!--添加mysql驱动-->
  	<dependency>
  		<groupId>mysql</groupId>
  		<artifactId>mysql-connector-java</artifactId>
  		<version>5.1.38</version>
  	</dependency>

步骤【2】 : mybatis全局配置文件

在项目src/main/resources目录下创建mybatis目录,在mybatis目录下新建mybatis-config.xml文件. 此文件主要配置一些全局的属性:查询缓存是否开启、缓存的作用域、延迟加载等,自定义TypeHandler、Interceptor、映射POJO和对应的mapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!-- Copyright 2009-2012 The MyBatis Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License 
	at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
	CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -->
<!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" />
		<!-- 全局启用或禁用延迟加载。当禁用时, 所有关联对象都会即时加载 -->
		<setting name="lazyLoadingEnabled" value="true" />
		<!-- 允许或不允许多种结果集从一个单独 的语句中返回(需要适合的驱动) -->
		<setting name="multipleResultSetsEnabled" value="true" />
		<!-- 使用列标签代替列名。 不同的驱动在这 方便表现不同。 参考驱动文档或充分测 试两种方法来决定所使用的驱动 -->
		<setting name="useColumnLabel" value="true" />
		<!-- 允许 JDBC 支持生成的键。 需要适合的 驱动。 如果设置为 true 则这个设置强制 生成的键被使用, 尽管一些驱动拒绝兼 容但仍然有效(比如 Derby) -->
		<setting name="useGeneratedKeys" value="false" />
		<!-- 配置默认的执行器。SIMPLE 执行器没 有什么特别之处。REUSE 执行器重用 预处理语句。BATCH 执行器重用语句 和批量更新 -->
		<setting name="defaultExecutorType" value="SIMPLE" />
		<!-- 设置超时时间, 它决定驱动等待一个数 据库响应的时间 -->
		<setting name="defaultStatementTimeout" value="100" />
		<setting name="safeRowBoundsEnabled" value="false" />
		<setting name="mapUnderscoreToCamelCase" value="false" />
		<setting name="localCacheScope" value="SESSION" />
		<setting name="jdbcTypeForNull" value="OTHER" />
		<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" />
	</settings>

        <!-- 在mappers定义之前 -->
	<typeHandlers>
	</typeHandlers>

        <!--映射POJO-->
	<typeAliases>
		
	</typeAliases>

        <!--指定mapper.xml路径-->
	<mappers>
		
	</mappers>

</configuration>

步骤【3】: mybatis与spring集成配置

【3.1】在项目src/main/resources目录下创建jdbc.properties文件,此文件配置数据库连接信息等内容

#mysql驱动
jdbc.driverClassName=com.mysql.jdbc.Driver
#连接地址
jdbc.url=jdbc:mysql://IP或域名:端口/数据库?useUnicode=true&characterEncoding=utf8&&zeroDateTimeBehavior=convertToNull
#用户名
jdbc.username=
#密码
jdbc.password=

【3.2】在项目src/main/resources下面创建名为spring的目录,然后在spring目录下创建文件spring-mybatis.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	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.2.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

        <!--引用外部文件,jdbc.properties配置了MYSQL连接信息:用户名/密码等-->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	<!-- 基于Druid数据库链接池的数据源配置 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="clone">
		<!-- 基本属性driverClassName、 url、user、password -->
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		
		<!-- 配置初始化大小、最小、最大 -->
		<!-- 通常来说,只需要修改initialSize、minIdle、maxActive -->
		<!-- 初始化时建立物理连接的个数,缺省值为0 -->
		<property name="initialSize" value="2" />
		<!-- 最小连接池数量 -->
		<property name="minIdle" value="2" />
		<!-- 最大连接池数量,缺省值为8 -->
		<property name="maxActive" value="10" />

		<!-- 获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁。 -->
		<property name="maxWait" value="60000" />
		
		<!-- 
			有些数据库连接的时候有超时限制(MySQL连接在8小时后断开),或者由于网络中断等原因,连接池的连接会出现失效的情况,这时候可以设置一个testWhileIdle参数为true,
			如果检测到当前连接不活跃的时间超过了timeBetweenEvictionRunsMillis,则去手动检测一下当前连接的有效性,在保证确实有效后才加以使用。
			在检测活跃性时,如果当前的活跃时间大于minEvictableIdleTimeMillis,则认为需要关闭当前连接。当
			然,为了保证绝对的可用性,你也可以使用testOnBorrow为true(即在每次获取Connection对象时都检测其可用性),不过这样会影响性能。
		-->
		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒(3600000:为1小时) -->
		<property name="timeBetweenEvictionRunsMillis" value="3600000" />
		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒(300000:为5分钟) -->
		<property name="minEvictableIdleTimeMillis" value="300000" />
		<!-- 用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用。 -->
		<!-- <property name="validationQuery" value="${jdbc.pool.validationQuery}" /> -->
		<!-- 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。建议配置为true,不影响性能,并且保证安全性。-->
      	<property name="testWhileIdle" value="true" />
      	<!-- 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。缺省值:true -->
      	<property name="testOnBorrow" value="false" />
      	<!-- 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。缺省值:false -->
      	<property name="testOnReturn" value="false" />
      	
      	<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
		<!-- 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql5.5以下的版本中没有PSCache功能,建议关闭掉。5.5及以上版本有PSCache,建议开启。缺省值:false -->
		<property name="poolPreparedStatements" value="true" />
		<!-- 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100。 -->
		<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
	</bean>
	
	<!-- 将数据源映射到sqlSessionFactory中 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
                <!--此处设置mybatis全局配置的路径-->
		<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<!--======= 事务配置 Begin ================= -->
	<!-- 事务管理器(由Spring管理MyBatis的事务) -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 关联数据源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 注解事务 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
	<!--======= 事务配置 End =================== -->

</beans>

【3.3】在spring目录下创建application.xml文件,此文件为spring主配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	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/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
   		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://code.alibabatech.com/schema/dubbo        
		http://code.alibabatech.com/schema/dubbo/dubbo.xsd"
		default-autowire="byName"
	>
    <!-- 采用注解的方式注入bean -->  
	<context:annotation-config/>  
	<!-- 配置要扫描的包,在配置的包路径下面的Bean才会被spring扫描 -->
    <context:component-scan base-package="aaa.bbb"/>
    <!-- 引入mybatis配置 -->
    <import resource="spring/spring-mybatis.xml"/>
</beans>

以上3个大步骤完成后,mybatis和spring的配置文件就结束了,下面就开始在代码中如何使用mybatis进行数据库操作,并且编写mapper文件并将mapper文件配置到mybatis-config.xml文件中的

步骤【4】: 使用mybatis进行数据库操作

【4.1】 创建POJO User

public class User {

	private Long id;
	private String name;
	private Date createTime;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", createTime=" + createTime + "]";
	}
}

【4.2】 创建UserDAO接口

public interface UserDAO {

	public User get(Long id);
	
	public User getByName(String name);
}

【4.3】创建UserDAO实现类UserDAOImpl.java

@Repository("userDAO")
public class UserDAOImpl extends SqlSessionDaoSupport implements UserDAO {

        //注入在spring-mybatis.xml中配置的sqlSessionFactory
	@AutoWired
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory){
		super.setSqlSessionFactory(sqlSessionFactory);
	}
	
	@Override
	public User get(Long id) {
		return getSqlSession().selectOne("User.get", id);
	}

	@Override
	public User getByName(String name) {
		return getSqlSession().selectOne("User.getByName",name);
	}

}

【4.4】创建UserMapper.xml文件

在mybatis目录下创建mapper目录,并在mapper目录下创建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="User">
        <!--通过用户ID查询用户-->
	<select id="get" resultType="User" parameterType="Long">
		SELECT * FROM User WHERE id = #{id}
	</select>
	<!--通过用户名查询用户-->
	<select id="getByName" resultType="User" parameterType="String">
		SELECT * FROM User WHERE name = #{name} 
	</select>
</mapper>

【4.5】将User和UserMapper.xml配置到mybatis-config.xml文件中

在mybatis-config.xml <typeAliases></typeAliases>标签内添加子标签 typeAlias

<typeAliases>
		<typeAlias type="包名.User" alias="User"/>
	</typeAliases>

在mybatis-config.xml <mappers></mappers>标签内添加子标签 mapper

<mappers>
		<mapper resource="mybatis/mapper/UserMapper.xml" />
	</mappers>

步骤【5】: 编写测试

【5.1】自己在MYSQL中创建user表并且至少添加一条测试记录

【5.2】引入spring-test和junit,在pom文件中添加

       <dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-test</artifactId>
  		<version>4.2.3.RELEASE</version>
  		<scope>test</scope>
  	</dependency>
  	<dependency>
	    <groupId>junit</groupId>
	    <artifactId>junit</artifactId>
	    <version>4.8.1</version>
	    <scope>test</scope>
	</dependency>

【5.3】在src/test/java创建MybatisSpringTest .java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application.xml")
public class MybatisSpringTest {

	@Autowired
	private UserDAO userDAO;
	
	@Test
	public void test() 
	{
		User user = userDAO.get(1566L);
		
		System.err.println(user);
		
		user = userDAO.getByName("Ttttyyyy");
		
		System.err.println(user);
		
	}
}

成功打印出user信息即代表成功

转载于:https://my.oschina.net/u/3382708/blog/918537

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值