MyBatis 3 – Spring集成教程

作为本教程的第一步(带有MyBatis 3的Spring MVC 3 CRUD示例),我们将定义一个MyBatis服务,该服务将帮助我们在数据库上执行CRUD操作。

我们有一个用于User的域类和一个用于将User信息存储在数据库中的数据库表。 在示例中,我们将使用xml配置模型来定义将执行CRUD操作的SQL命令。

我们的领域类

package com.raistudies.domain;

import java.io.Serializable;

public class User implements Serializable{

    private static final long serialVersionUID = 3647233284813657927L;

    private String id;
    private String name = null;
    private String standard = null;
    private String age;
    private String sex = null;

    //setter and getter have been omitted to make the code short

    @Override
    public String toString() {
        return "User [name=" + name + ", standard=" + standard + ", age=" + age
        + ", sex=" + sex + "]";
    }
}

我们的域类中有五个属性,它们称为User,它们必须为其提供数据库服务。

我们的数据库表

以下是我们的数据库表:

CREATE TABLE `user` (
    `id` varchar(36) NOT NULL,
    `name` varchar(45) DEFAULT NULL,
    `standard` varchar(45) DEFAULT NULL,
    `age` varchar(45) DEFAULT NULL,
    `sex` varchar(45) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

创建CRUD操作的界面

为了使用MyBatis 3定义CRUD数据库操作,我们必须指定将用于执行CRUD操作的方法。 以下是我们示例的界面:

package com.raistudies.persistence;

import java.util.List;

import com.raistudies.domain.User;

public interface UserService {

    public void saveUser(User user);
    public void updateUser(User user);
    public void deleteUser(String id);
    public List<User> getAllUser();
}

我们这里有四种方法来执行创建,更新,删除和从数据库获取操作。

UserService接口的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.raistudies.persistence.UserService">

    <resultMap id="result" type="user">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="standard" column="standard"/>
        <result property="age" column="age"/>
        <result property="sex" column="sex"/>
    </resultMap>

    <select id="getAllUser" parameterType="int" resultMap="result">
        SELECT id,name,standard,age,sex
        FROM user;
    </select>

    <insert id="saveUser" parameterType="user">
        INSERT INTO user (id,name,standard,age,sex)
        VALUE (#{id},#{name},#{standard},#{age},#{sex})
    </insert>

    <update id="updateUser" parameterType="user">
        UPDATE user
        SET
        name = #{name},
        standard = #{standard},
        age = #{age},
        sex = #{sex}
        where id = #{id}
    </update>

    <delete id="deleteUser" parameterType="int">
        DELETE FROM user
        WHERE id = #{id}
    </delete>
</mapper>

您会在这里看到很多新东西:

映射文件将包含元素<mapper />来定义服务的SQL语句。 在这里,属性“ 名称空间 ”定义了已为其定义此映射文件的接口。

<insert />标记定义该操作为插入类型。 “ id ”属性的值指定为其定义了SQL语句的函数名称。 这里是“ saveUser ”。 属性“ parameterType ”定义方法的参数是哪种类型。 我们在这里为User类使用了别名。 稍后将在MyBatis配置文件中配置别名。 然后,我们必须定义SQL语句。 #{id}定义将类User的属性“ id ”作为参数传递给SQL查询。

<resultMap />标记用于指定User类和用户表之间的映射。 <resultMap />的id是映射定义的唯一名称。 在此标签下,我们定义了不同的属性以及将哪个列绑定到哪个属性。

<select />标记用于指定选择SQL语句。 “ id ”属性的值指定为其定义了SQL语句的函数名称。

属性resultMap用于将SQL语句的返回类型定义为一个集合。

MyBatis 3配置文件

以下是我们的MyBatis配置文件:

<?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>
        <!-- changes from the defaults -->
       <setting name="lazyLoadingEnabled" value="false" />
    </settings>
    <typeAliases>
        <typeAlias type="com.raistudies.domain.User" alias="user"/>
    </typeAliases>
</configuration>

您可以看到,我们尚未在此处定义一些非常重要的属性:

  1. 数据库连接属性。
  2. 与交易相关的属性。
  3. 并且也没有定义映射器配置。

MyBatis 3是一个非常强大的SQL映射框架,它使用用户定义的服务的代理实现自动生成数据库访问类。 如果您将MyBatis 3与Spring框架集成并使用这些代理实现,我们就会意识到这是真正的力量。 这将使我们的数据库工作减少80%。 在下面,我们将看到如何将MyBatis 3与Spring 3框架集成在一起。 以前,我们使用MyBatis 3为User类创建了CRUD数据库服务。现在,我们将使用MyBatis与Spring框架集成的数据服务进行集成。

使用的工具:

  • c3p0-0.9.1.2.jar –用于提供池化数据库连接。
  • mybatis-spring-1.0.0.jar –用于将MyBatis与Spring集成(由MyBatis团队提供)
  • Spring JDBC和Core库

要集成这两个框架,我们必须遵循以下步骤:

步骤1:将数据源定义为Spring bean
由于我们将使用c3po数据源提供程序,因此我们必须在Spring中定义数据源bean。 以下是配置代码段:

<!-- Declare a datasource that has pooling capabilities -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close" p:driverClass="${app.jdbc.driverClassName}"
p:jdbcUrl="${app.jdbc.url}" p:user="${app.jdbc.username}" p:password="${app.jdbc.password}"
p:acquireIncrement="10" p:idleConnectionTestPeriod="60" p:maxPoolSize="100"
p:maxStatements="50" p:minPoolSize="10" />

在这里,我们创建了一个带有com.mchange.v2.c3p0.ComboPooledDataSource类的id dataSource的spring bean,它由c3p0库提供用于合并数据源。

我们在bean中设置了一些属性。 以下是在bean中定义的属性的描述:

  • driverClass :将用于连接数据库的驱动程序类。
  • jdbcUrl :jdbc定义数据库连接字符串的URL。
  • user :数据库用户的用户名。
  • password :数据库用户的密码。
  • acquisitionIncrement :在连接短缺的情况下,一次将创建多少个连接。
  • idleConnectionTestPeriod :连接断开多长时间后,如果不再使用它,它将被关闭。
  • maxPoolSize :可以创建的最大连接数。
  • maxStatements :连接上要执行的最大SQL语句数。
  • minPoolSize :要创建的最小连接数。

我们已经使用Spring EL定义了许多属性值,这些属性值将从属性文件中获取。

在Spring定义交易管理器

我们将使用Spring JDBC框架提供的用户事务管理器,为了定义事务级别,我们将使用注释。 以下是事务管理器的配置:

<!-- Declare a transaction manager -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource" />

<!-- Enable annotation style of managing transactions -->
<tx:annotation-driven transaction-manager="transactionManager" />

定义MyBatis SqlSessionFactory和MapperScanner

<!-- define the SqlSessionFactory, notice that configLocation is not needed when you use MapperFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="WEB-INF/mybatis/sqlmap-config.xml" />
</bean>

<!-- scan for mappers and let them be autowired -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="${MapperInterfacePackage}" />
</bean>

SqlSessionFactory bean将提供MyBatis的SessionFactory实例。 要配置SqlSessionFactory,我们需要定义两个属性。 首先,MyBatis将使用其创建连接数据库的数据源和MyBatis配置文件名来配置MyBatis的环境。

MapperScannerConfigurer用于发布定义为MyBatis的数据服务接口,以配置为Spring Bean。 我们只需要提供定义接口及其映射XML文件的程序包即可。 我们可以使用通用分隔符或分号指定多个软件包。 之后,我们将能够使用@Autowired批注获取UserService的实例。 我们不必实现该接口,因为MyBatis将为此提供代理实现。

Spring配置文件一起
这是我们的jdbc-context.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:p="http://www.springframework.org/schema/p"
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.0.xsd

http://www.springframework.org/schema/tx

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

http://www.springframework.org/schema/context

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

">

<context:property-placeholder location="/WEB-INF/jdbc.properties,/WEB-INF/mybatis/mybatis.properties" />

    <!-- Enable annotation style of managing transactions -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- Declare a datasource that has pooling capabilities -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close" p:driverClass="${app.jdbc.driverClassName}"
    p:jdbcUrl="${app.jdbc.url}" p:user="${app.jdbc.username}" p:password="${app.jdbc.password}"
    p:acquireIncrement="10" p:idleConnectionTestPeriod="60" p:maxPoolSize="100"
    p:maxStatements="50" p:minPoolSize="10" />

    <!-- Declare a transaction manager -->
    <bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
    p:dataSource-ref="dataSource" />

    <!-- define the SqlSessionFactory, notice that configLocation is not needed when you use MapperFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="WEB-INF/mybatis/sqlmap-config.xml" />
    </bean>

    <!-- scan for mappers and let them be autowired -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="${MapperInterfacePackage}" />
    </bean>

</beans>

jdbc.properties文件

# database properties
app.jdbc.driverClassName=com.mysql.jdbc.Driver
app.jdbc.url=jdbc:mysql://localhost/mybatis-example
app.jdbc.username=root
app.jdbc.password=password

mybatis.properties文件

MapperInterfacePackage=com.raistudies.persistence

参考: 使用我们的JCG合作伙伴 使用MyBatis 3映射框架创建CRUD服务-第1部分集成MyBatis 3和Spring框架-第2部分   Rai Studies博客上的Rahul Mondal。


翻译自: https://www.javacodegeeks.com/2012/02/mybatis-3-spring-integration-tutorial.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值