spring整合mybatis怎样配置注解

spring整合mybatis怎样配置注解,第1张

mybatis和spring的整合步骤:

1)使用mybatis,必须有个全局配置文件configuration.xml,来配置mybatis的缓存,延迟加载等等一系列属性,该配置文件示例如下:

Java代码

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

<!DOCTYPE configuration

PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"

"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">

<configuration>

<settings>

<!-- 全局映射器启用缓存 -->

<setting name="cacheEnabled" value="true" />

<!-- 查询时,关闭关联对象即时加载以提高性能 -->

<setting name="lazyLoadingEnabled" value="true" />

<!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->

<setting name="aggressiveLazyLoading" value="false" />

<!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->

<setting name="multipleResultSetsEnabled" value="true" />

<!-- 允许使用列标签代替列名 -->

<setting name="useColumnLabel" value="true" />

<!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->

<setting name="useGeneratedKeys" value="true" />

<!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->

<setting name="autoMappingBehavior" value="FULL" />

<!-- 对于批量更新 *** 作缓存SQL以提高性能 -->

<setting name="defaultExecutorType" value="BATCH" />

<!-- 数据库超过25000秒仍未响应则超时 -->

<setting name="defaultStatementTimeout" value="25000" />

</settings>

<!-- 全局别名设置,在映射文件中只需写别名,而不必写出整个类路径 -->

<typeAliases>

<typeAlias alias="TestBean"

type="com.wotao.taotao.persist.test.dataobject.TestBean" />

</typeAliases>

<!-- 非注解的sql映射文件配置,如果使用mybatis注解,该mapper无需配置,但是如果mybatis注解中包含@resultMap注解,则mapper必须配置,给resultMap注解使用 -->

<mappers>

<mapper resource="persist/test/orm/test.xml" />

</mappers>

</configuration>

2)该文件放在资源文件的任意classpath目录下,假设这里就直接放在资源根目录,等会spring需要引用该文件。

查看ibatis-3-config.dtd发现除了settings和typeAliases还有其他众多元素,比如properties,objectFactory,environments等等,这些元素基本上都包含着一些环境配置,数据源定义,数据库事务等等,在单独使用mybatis的时候非常重要,比如通过以构造参数的形式去实例化一个sqlsessionFactory,就像这样:

Java代码

SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader)

SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, properties)

SqlSessionFactory factory = sqlSessionFactoryBuilder.build(reader, environment, properties)

而typeHandlers则用来自定义映射规则,如可以自定义将Character映射为varchar,plugins元素则放了一些拦截器接口。

2)在spring配置文件中指定c3p0数据源定义如下:

Java代码

<!-- c3p0 connection pool configuration -->

<bean id="testDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"

destroy-method="close">

<!-- 数据库驱动 -->

<property name="driverClass" value="${db.driver.class}" />

<!-- 连接URL串 -->

<property name="jdbcUrl" value="${db.url}" />

<!-- 连接用户名 -->

<property name="user" value="${db.username}" />

<!-- 连接密码 -->

<property name="password" value="${db.password}" />

<!-- 初始化连接池时连接数量为5个 -->

<property name="initialPoolSize" value="5" />

<!-- 允许最小连接数量为5个 -->

<property name="minPoolSize" value="5" />

<!-- 允许最大连接数量为20个 -->

<property name="maxPoolSize" value="20" />

<!-- 允许连接池最大生成100个PreparedStatement对象 -->

<property name="maxStatements" value="100" />

<!-- 连接有效时间,连接超过3600秒未使用,则该连接丢弃 -->

<property name="maxIdleTime" value="3600" />

<!-- 连接用完时,一次产生的新连接步进值为2 -->

<property name="acquireIncrement" value="2" />

<!-- 获取连接失败后再尝试10次,再失败则返回DAOException异常 -->

<property name="acquireRetryAttempts" value="10" />

<!-- 获取下一次连接时最短间隔600毫秒,有助于提高性能 -->

<property name="acquireRetryDelay" value="600" />

<!-- 检查连接的有效性,此处小弟不是很懂什么意思 -->

<property name="testConnectionOnCheckin" value="true" />

<!-- 每个1200秒检查连接对象状态 -->

<property name="idleConnectionTestPeriod" value="1200" />

<!-- 获取新连接的超时时间为10000毫秒 -->

<property name="checkoutTimeout" value="10000" />

</bean>

配置中的${}都是占位符,在指定数据库驱动打war时会自动替换,替换的值在父pom中配置。

3)需要一个sessionFactory来生成session,sessionFactory配置如下:

Java代码

<bean id="testSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="configLocation" value="classpath:configuration.xml" />

<property name="dataSource" ref="testDataSource" />

</bean>

4)配置一个映射器接口来对应sqlSessionTemplate,该映射器接口定义了接口方法:

Java代码

<!-- data OR mapping interface -->

<bean id="testMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">

<property name="sqlSessionFactory" ref="testSqlSessionFactory" />

<property name="mapperInterface" value="com.wotao.taotao.persist.test.mapper.TestMapper" />

</bean>

5)至此,一个完整的myabtis整合spring的配置文件看起来应该如下所示:

Java代码

<?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" xmlns:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

<!-- c3p0 connection pool configuration -->

<bean id="testDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"

destroy-method="close">

<property name="driverClass" value="${db.driver.class}" />

<property name="jdbcUrl" value="${db.url}" />

<property name="user" value="${db.username}" />

<property name="password" value="${db.password}" />

<property name="initialPoolSize" value="5" />

<property name="minPoolSize" value="5" />

<property name="maxPoolSize" value="20" />

<property name="maxStatements" value="100" />

<property name="maxIdleTime" value="3600" />

<property name="acquireIncrement" value="2" />

<property name="acquireRetryAttempts" value="10" />

<property name="acquireRetryDelay" value="600" />

<property name="testConnectionOnCheckin" value="true" />

<property name="idleConnectionTestPeriod" value="1200" />

<property name="checkoutTimeout" value="10000" />

</bean>

<bean id="testSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="configLocation" value="classpath:configuration.xml" />

<property name="dataSource" ref="testDataSource" />

</bean>

<!-- data OR mapping interface -->

<bean id="testMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">

<property name="sqlSessionFactory" ref="testSqlSessionFactory" />

<property name="mapperInterface" value="com.wotao.taotao.persist.test.mapper.TestMapper" />

</bean>

<!-- add your own Mapper here -->

<!-- comment here, using annotation -->

<!-- <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">-->

<!-- <constructor-arg index="0" ref="sqlSessionFactory" />-->

<!-- </bean>-->

<!-- base DAO class, for module business, extend this class in DAO -->

<!-- <bean id="testBaseDAO" class="com.test.dao.TestBaseDAO">-->

<!-- <property name="sqlSessionTemplate" ref="sqlSessionTemplate" />-->

<!-- </bean>-->

<!-- <bean id="testDAO" class="com.test.dao.impl.TestDAOImpl" />-->

<!-- you can DI Bean if you don't like use annotation -->

</beans>

mybatis

+spring时的mybatis拦截器需要加注解。加注解的方法是用注释符号'。

一、添加注释的方法。

要添加注释,只需要用单引号’作为注释文字的开头。注释符号告诉Visual

Basic,忽略这个符号后面的内容,这些内容就是代码段中的注释部分,既是为了方便开发者,也是为了方便以后可能检查源代码的其它程序员。注释在代码编辑器中以绿色字符显示。

二、添加注释的注意事项。

注释可以和语句在同一行,写在语句的后面,也可占据一整行。但不能在同一行上把注释接在续行符之后。

mybatis最初配置信息是基于 XML ,映射语句(SQL)也是定义在 XML 中的。而到了 MyBatis 3提供了新的基于注解的配置。

这里讲述 注解开发方式:

首先我们需要获取 SqlSession :

参数设置为 true 表示开启自动提交模式。

session 在注解形式的使用方式如:

所以mybatis 的使用使用三部分:

这里主要讲解 Mapper 层的开发规则。

sql 类型主要分成 : select @Select(${sql}) , update @Update(${sql}) , insert @Insert($sql) , delete (${sql}) .

@Results 用来设置table信息与bean相关字段的映射关系, 每一个字段的关系使用 @Result 控制。

默认情况下对于每一table字段,例如 name , 会调用 bean 中的 setName(..) . 如果找不到,对于新版本的 mybatis 会报错。

例如上面的 cluster_name 会调用 setCluster_name() . 但是java 中使用的 clusterName ,可以通过 Result 注解控制.

@ResultMap 可以通过Id,应用其他的 Results

还有一种更改映射的方式:

mapUnderscoreToCamelCase 设置为true, 之后会自动实现 mysql 中的unix命名方式转为java的驼峰表示法。

@MapKey 此注解应用将查询数据转为 Map<>, 注意的是MapKey()中的id最终调用bean的getId 获取数据,所以需要映射bean字段而不是table.

@Param注解用于给方法参数起一个名字。以下是笔者总结的使用原则:

在方法只接受一个参数的情况下,可以不使用@Param。

在方法接受多个参数的情况下,建议一定要使用@Param注解给参数命名。

insert 时获取自增主键的方式:

法一:

法二:

#{} 的作用主要是替换预编译语句(PrepareStatement)中的占位符 ? :

对于 : INSERT INTO user (name) VALUES (#{name}) ==> INSERT INTO user (name) VALUES (?)

${} 符号的作用是直接进行字符串替换:

对于 : INSERT INTO user (name) VALUES ('${name}') ==> INSERT INTO user (name) VALUES ('tianshozhi')


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11855570.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存