【mybatis】基本配置和使用

本文深入解析了Maven环境下MyBatis的引入、配置文件使用、SQL语句编写、Spring集成以及相关配置,包括配置文件mybatisconfig.xml、数据源配置、SQLSessionFactory、事务管理等关键步骤,提供了从入门到进阶的全面指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.maven引用

                <!-- mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>   <!-- 整合spring -->
			<version>1.2.1</version>
		</dependency>

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

		<dependency>
			<groupId>org.mybatis.caches</groupId>
			<artifactId>mybatis-ehcache</artifactId>
			<version>1.0.3</version>
		</dependency>

2.mybatis涉及到的配置文件

         A.mybatisconfig.xml  :eclipse放在src下的xml配置文件:用于设置编写sql语句的xml配置文件(如Sales——>sales.xml)的mapper,包的别名typeAliases以及其他的一些设置

                    eg:

<?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.sales.entity"/>
        <!--<typeAliase type="" aliase="" >-->
 </typeAliases>
	<mappers>
 	<mapper resource="com/xxx/sales/front/repository/mybatis/sales.xml"/>
        <mapper resource="com/xxx/sales/front/repository/mybatis/saleOrder.xml"/>
        <mapper resource="com/xxx/sales/front/repository/mybatis/distributorAccount.xml"/>
        <mapper resource="com/xxx/sales/front/repository/mybatis/snsUser.xml"/>
        <mapper resource="com/xxx/sales/front/repository/mybatis/rechargeOrder.xml"/>
        <mapper resource="com/xxx/sales/front/repository/mybatis/poster.xml"/>
        <mapper resource="com/xxx/sales/front/repository/mybatis/withdrawRecord.xml"/>
        <mapper resource="com/xxx/sales/front/repository/mybatis/flowProduct.xml"/>
	</mappers>
</configuration>

       B.在spring配置文件中的配置

<?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:p="http://www.springframework.org/schema/p" 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-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.xsd">
	
 	<context:property-placeholder location="classpath:sysconfig.properties" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close" p:driverClassName="${jdbc.mysql.driverClassName}"
		p:url="${jdbc.mysql.url}" p:username="${jdbc.mysql.username}"
		p:password="${jdbc.mysql.password}" p:maxActive="100000" p:maxIdle="10"
		p:testOnBorrow="true" p:validationQuery="select 1" >

		<description>开发环境本地库配置</description>
	</bean>
	

	<span style="color:#FF0000;"><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
		p:dataSource-ref="dataSource" p:configLocation="classpath:mybatisconfig.xml" />

	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory" />
	</bean></span>

	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
		p:dataSource-ref="dataSource" />
	
		
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="update*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="mod*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="insert*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="save*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="find*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="load*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="query*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="export*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="modify*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="cancle*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="logout*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>

	<!-- 通过AOP实现横向切入 -->
	
	<aop:config>
		<aop:advisor pointcut="execution(* com.xxx.sales.*.service.*.*(..))" advice-ref="txAdvice" />
	</aop:config>
</beans>



       C.编写sql语句(增删改查)的xml文件,每个javabean对应一个xml文件

      eg.

<?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.sales.entity.DistributorAccount">
    <resultMap id="distributorAccountResultMap" type="distributorAccount">
        <id property="id" column="id"></id>
        <result property="operatorId" column="operator_id"></result>
        <result property="orderNo" column="orderno"></result>
        <result property="price" column="price"></result>
        <result property="mobile" column="mobile"></result>
        <result property="flowPackage" column="flow_package"></result>
        <result property="operatorType" column="operator_type"></result>
        <result property="status" column="status"></result>
        <result property="createdDate" column="created_date"></result>
        <result property="finishDate" column="finish_date"></result>
        <result property="lastModified" column="last_modified"></result>
        <result property="remark" column="remark"></result>
        <result property="sellerId" column="seller_id"></result>
        <result property="version" column="version"></result>
        <result property="refundOperatorId" column="refund_operator_id"></result>
    </resultMap>

    <select id="selectDistributorAccountList" parameterType="distributorAccountForm" resultMap="distributorAccountResultMap">
        select o.* from rp_app_account o
        <where>
              o.seller_id = #{operatorId}
            <if test="beginDateStr != null and beginDateStr != ''">
                AND DATE_FORMAT(o.last_modified,'%Y-%m-%d') >= str_to_date(#{beginDateStr},'%Y-%m-%d')
            </if>
            <!--%Y-%m-%d %H:%i:%s-->
            <if test="endDateStr != null and endDateStr != ''">
                <![CDATA[
                and DATE_FORMAT(o.last_modified,'%Y-%m-%d') <= str_to_date(#{endDateStr},'%Y-%m-%d')
                ]]>
            </if>
            <if test="operatorType != null and operatorType != ''">
                and o.operator_type = #{operatorType}
            </if>
        </where>
        order by o.last_modified desc
        limit #{offset},#{pageSize}
    </select>

    <insert id="saveDistributorAccount" >
        insert into rp_app_account (operator_id,orderno,price,mobile,flow_package,operator_type,status,created_date,finish_date,last_modified,remark,seller_id,version)
        values (#{operatorId},#{orderNo},#{price},#{mobile},#{flowPackage},#{operatorType},#{status},now(),#{finishDate},now(),#{remark},#{sellerId},#{version})
    </insert>

    <update id="updateStatusByOrderNo" >
        update rp_app_account set status = #{status} ,last_modified = now(),refund_operator_id = #{refundOperatorId} where orderno = #{orderNo}
    </update>
</mapper>

          D.编写Dao、DaoImpl

         AccountDao.java

public interface AccountDao {

    List<DistributorAccount> findDistributorAccountByCondition(DistributorAccountForm distributorAccountForm);
}



        AccountDaoImpl.java

<pre name="code" class="java">@Repository
public class AccountDaoImpl extends AbstractMyBatisBaseRepository implements AccountDao {
    /**
     * 查询账单
     * @param distributorAccountForm
     * @return
     */
    @Override
    public List<DistributorAccount> findDistributorAccountByCondition(DistributorAccountForm distributorAccountForm) {
        return getSqlSession().selectList("com.raipeng.sales.entity.DistributorAccount.selectDistributorAccountList",distributorAccountForm,new RowBounds(0,5));
    }

}


       E.测试

import com.raipeng.sales.entity.DistributorAccount;
import com.raipeng.sales.entity.WithdrawRecord;
import com.raipeng.sales.entity.form.DistributorAccountForm;
import com.raipeng.sales.front.repository.AccountDao;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by 111 on 2015/11/26.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
@TransactionConfiguration(transactionManager = "transactionManager",defaultRollback = true)
@Transactional
public class DistributorAccountDaoTest {

    @Autowired
    private AccountDao accountDao;

    @Test
    public void findTest(){
        DistributorAccountForm distributorAccountForm = new DistributorAccountForm();
        distributorAccountForm.setBeginDateStr("2015-11-26 06:28:00");
        distributorAccountForm.setEndDateStr(null);
        distributorAccountForm.setOperatorType(1);
        List<DistributorAccount> distributorAccountList = accountDao.findDistributorAccountByCondition(distributorAccountForm);
        System.out.println(distributorAccountList.size());
    }
}


内容概要:本文探讨了在MATLAB/SimuLink环境中进行三相STATCOM(静态同步补偿器)无功补偿的技术方法及其仿真过程。首先介绍了STATCOM作为无功功率补偿装置的工作原理,即通过调节交流电压的幅值相位来实现对无功功率的有效管理。接着详细描述了在MATLAB/SimuLink平台下构建三相STATCOM仿真模型的具体步骤,包括创建新模型、添加电源负载、搭建主电路、加入控制模块以及完成整个电路的连接。然后阐述了如何通过对STATCOM输出电压电流的精确调控达到无功补偿的目的,并展示了具体的仿真结果分析方法,如读取仿真数据、提取关键参数、绘制无功功率变化曲线等。最后指出,这种技术可以显著提升电力系统的稳定性与电能质量,展望了STATCOM在未来的发展潜力。 适合人群:电气工程专业学生、从事电力系统相关工作的技术人员、希望深入了解无功补偿技术的研究人员。 使用场景及目标:适用于想要掌握MATLAB/SimuLink软件操作技能的人群,特别是那些专注于电力电子领域的从业者;旨在帮助他们学会建立复杂的电力系统仿真模型,以便更好地理解STATCOM的工作机制,进而优化实际项目中的无功补偿方案。 其他说明:文中提供的实例代码可以帮助读者直观地了解如何从零开始构建一个完整的三相STATCOM仿真环境,并通过图形化的方式展示无功补偿的效果,便于进一步的学习与研究。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值