mybatis的使用

  • 单独使用

1、 引入jar包

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>x.x.x</version>
</dependency>

2、编写mybatis-config.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>
    <properties resource="db.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/gaojl/mapper/PaymentMapper.xml"/>
    </mappers>
</configuration>

3、 构建SqlSessionFactory

每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。
从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。 但也可以使用任意的输入流(InputStream)实例,比如用文件路径字符串或 file:// URL 构造的输入流。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,使得从类路径或其它位置加载资源文件更加容易。

      	String resource = "mybatis-config.xml";
        InputStream in = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        //true代表自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        PaymentMapper paymentMapper = sqlSession.getMapper(PaymentMapper.class);
  • 与spring 整合
    1、引入jar
 <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
            <scope>provided</scope>
        </dependency>

注意有可能需要静态资源的过滤

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

2、Mapper文件 (接口以及 xml)

public interface PaymentMapper1 {
    List<Payment> selectPayment();
    int insert(Payment payment);
    void delete(long id);
}
<?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.gaojl.mapper.PaymentMapper1">
    <select id="selectPayment" resultType="com.gaojl.entity.Payment">
        select * from payment
    </select>
    <insert id="insert" parameterType="com.gaojl.entity.Payment" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
        insert into payment(serial) values(#{serial})
    </insert>
    <delete id="delete" parameterType="long" >
        delete from payment where id = #{id}
    </delete>
</mapper>

还需要自己编写实现类并放入spring容器中

public class PaymentMapperImpl extends SqlSessionDaoSupport implements PaymentMapper1 {
    public List<Payment> selectPayment() {
        PaymentMapper1 paymentMapper = getSqlSession().getMapper(PaymentMapper1.class);
        Payment payment = new Payment("ppp");
        System.out.println(paymentMapper.insert(payment));

        int a = 1/0;
        paymentMapper.delete(payment.getId());
        return paymentMapper.selectPayment();
    }

    public int insert(Payment payment) {

        return getSqlSession().getMapper(PaymentMapper1.class).insert(payment);
    }

    public void delete(long id) {
        getSqlSession().getMapper(PaymentMapper1.class).delete(id);
    }
}

3、application.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/db2021?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="mybatis-config.xml"></property>
<!--        <property name="mapperLocations" value="classpath*:com/gaojl/mapper/**/*.xml"/>-->
    </bean>
    
    <bean id="paymentMapper1" class="com.gaojl.mapper.PaymentMapperImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

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

    <!--    结合Aop实现事务的织入-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <!--    给哪些方法配置事务    -->
        <tx:attributes>
            <!--            所有方法都支持事务-->
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* com.gaojl.mapper.PaymentMapperImpl.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"></aop:advisor>
    </aop:config>


</beans>

申明式事务
In Spring we can implement transaction in three ways:

Platform Transaction Management.
Declarative Transaction Management.
Programmatic Transaction Management.
What you implemented is called Declarative Transaction Management via XML.

In short you did the implementation of transaction by Spring’s AOP feature.

Coupling the tx:advice XML configuration with an XML based AOP configuration makes for synergistic combination. For example, we can use method names to automatically figure out what kind of transaction we want to apply on that method.

Say we want to apply the transaction on all that methods which start with save and modify such as savePizza(),saveColdDrink(),modifyOrder(),modifyBill(). For these we have to define the advice in our xml file:

<tx:advice id="txAdvice" >
  <tx:attributes>
    <tx:method name="save*" propagation="REQUIRED"/>
    <tx:method name="modify*" propagation="REQUIRED"/>
  </tx:attributes>
</tx:advice> 

Our advice is ready, as we said by using above line that we want transactions only on the methods which start with save or modify. Now we are going to say which beans require the above advice by using pointcut element of aop-config. For example let say we want to apply the transaction advice to all of the classes which are available inside the com.mytransaction.service package.

For this, we have to add the following line inside our xml file:

<aop:config>
  <aop:pointcut id="allServices"
    expression="execution(*com.mytransaction.service.*.*(..))"/>
  <aop:advisor advice-ref="txAdvice" pointcut-ref="allServices"/>
</aop:config>

In-short, tx:advice mean what to do or which behavior of transaction we want to apply. pointcut element inside says where we want to apply the transaction, say <aop:advisor advice-ref=“txAdvice” pointcut-ref=“allServices”/>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值