Spring + Mybatis 基本用法

Spring和Mybatis需要mybatis-spring-1.3.2.jar

Customer

package com.shpun.entity;
public class Customer {
    private String id;
    private String name;
    private String gender;
    private String birthday;
    private String tel;
    private String email;
    private String introduction;
    /*getter setter*/
}

CustomerMapper

package com.shpun.mapper;
@Repository  // 用于Spring掃描Mapper
public interface CustomerMapper {
    int insertCustomer(Customer customer);
    int deleteCustomer(String id);
    int updateCustomer(Customer customer);
    Customer selectCustomer(String id);
    List<Customer> selectAllCustomers();
}

CustomerMapper.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.shpun.mapper.CustomerMapper">

    <insert id="insertCustomer" useGeneratedKeys="true" keyProperty="id" parameterType="customer">
        insert into customers (name,gender,birthday,tel,email,introduction) value (#{name},#{gender},#{birthday},#{tel},#{email},#{introduction})
    </insert>

    <delete id="deleteCustomer" parameterType="string">
        delete from customers where id=#{id}
    </delete>

    <update id="updateCustomer" parameterType="customer">
        update customers set name=#{name},gender=#{gender},birthday=#{birthday},tel=#{tel},email=#{email},introduction=#{introduction} where id=#{id}
    </update>

    <select id="selectCustomer" parameterType="string" resultType="customer">
        select * from customers where id=#{id}
    </select>

    <select id="selectAllCustomers" resultType="customer">
        select * from customers
    </select>

</mapper>

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>

    <settings>
        <!-- 全局映射器啟用緩存 -->
        <setting name="cacheEnabled" value="true"/>
        <!-- 允許JDBC支持生成的鍵 -->
        <setting name="useGeneratedKeys" value="true"/>
        <!-- 配置默認(rèn)執(zhí)行器 Reuse 重用預(yù)處理語句 -->
        <setting name="defaultExecutorType" value="REUSE"/>
        <!-- 全局啟用延遲加載 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 設(shè)置超時時間辟躏,決定驅(qū)動等待一個數(shù)據(jù)庫相應(yīng)的時間 -->
        <setting name="defaultStatementTimeout" value="2500"/>
    </settings>

    <!-- 別名 -->
    <typeAliases>
        <typeAlias alias="customer" type="com.shpun.entity.Customer"/>
    </typeAliases>

    <!-- 映射器路徑 -->
    <mappers>
        <mapper resource="com/shpun/mapper/CustomerMapper.xml"/>
    </mappers>

</configuration>

spring-config.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 引入外部properties文件 -->
    <context:property-placeholder location="mysql.properties"/>

    <!-- 設(shè)置數(shù)據(jù)庫信息等 -->
    <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
    </bean>

    <!-- SqlSessionFactoryBean 去支持 SqlSessionFactory 配置 -->
    <bean  id="SqlSessionFactory"  class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dateSource"/>
        <property name="configLocation" value="mybatis-config.xml"/>
    </bean>

    <!-- 自動掃描配置Mapper的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定Spring掃描的包 -->
        <property name="basePackage" value="com.shpun.mapper"/>
        <!-- 指定Spring中SqlSessionFactory的Bean的名稱 -->
        <property name="SqlSessionFactoryBeanName" value="SqlSessionFactory"/>
        <!-- 指定類被注解標(biāo)識才掃描 @Repository -->
        <property name="annotationClass" value="org.springframework.stereotype.Repository"/>
    </bean>

</beans>

使用log4j需要配置log4j.properties

log4j.rootLogger=DEBUG,stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %c: %m%n

測試

package com.shpun.main;
public class TestMain {
    public static void main(String[] args){

        Logger logger = Logger.getLogger(TestMain.class);
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        CustomerMapper customerMapper = context.getBean(CustomerMapper.class);

        Customer customer = new Customer();
        customer.setName("test");
        customer.setIntroduction("test Spr Myb");

        customerMapper.insertCustomer(customer);
        logger.info("insert id : "+customer.getId());

        customerMapper.deleteCustomer("1028");

        customer.setId("1029");
        customer.setIntroduction("update 1029 修改成功");
        customerMapper.updateCustomer(customer);

        logger.info(customerMapper.selectCustomer("1029"));

        logger.info(customerMapper.selectAllCustomers());
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子眶俩,更是在濱河造成了極大的恐慌拄查,老刑警劉巖躺彬,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件咕痛,死亡現(xiàn)場離奇詭異簿姨,居然都是意外死亡距误,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進(jìn)店門扁位,熙熙樓的掌柜王于貴愁眉苦臉地迎上來准潭,“玉大人,你說我怎么就攤上這事域仇⌒倘唬” “怎么了?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵暇务,是天一觀的道長泼掠。 經(jīng)常有香客問我,道長垦细,這世上最難降的妖魔是什么择镇? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮括改,結(jié)果婚禮上腻豌,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好饲梭,可當(dāng)我...
    茶點故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布乘盖。 她就那樣靜靜地躺著,像睡著了一般憔涉。 火紅的嫁衣襯著肌膚如雪订框。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天兜叨,我揣著相機與錄音穿扳,去河邊找鬼。 笑死国旷,一個胖子當(dāng)著我的面吹牛矛物,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播跪但,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼履羞,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了屡久?” 一聲冷哼從身側(cè)響起忆首,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎被环,沒想到半個月后糙及,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡筛欢,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年浸锨,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片版姑。...
    茶點故事閱讀 39,769評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡柱搜,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出漠酿,到底是詐尸還是另有隱情冯凹,我是刑警寧澤谎亩,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布炒嘲,位于F島的核電站,受9級特大地震影響匈庭,放射性物質(zhì)發(fā)生泄漏夫凸。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一阱持、第九天 我趴在偏房一處隱蔽的房頂上張望夭拌。 院中可真熱鬧,春花似錦、人聲如沸鸽扁。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽桶现。三九已至躲雅,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間骡和,已是汗流浹背相赁。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留慰于,地道東北人钮科。 一個月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像婆赠,于是被迫代替她去往敵國和親绵脯。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容