spring-mybatis初使用

需要的lib文件如下


image.png

使用xml

包結(jié)構(gòu)


image.png
spring 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 https://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.ly1.service"/>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="url" value="jdbc:mysql://localhost:3306/test1"/>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="username" value="root"/>
        <property name="password" value="test.lwm"/>
    </bean>
    <bean id="personMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.ly1.mapper.PersonMapper"/>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

如上圖企锌,先配置一個sqlSessionFactoryBean,然后配置數(shù)據(jù)庫BasicDataSource扼雏,最后配置Mapper(MapperFactoryBean)
其他,Person是實體類
Mapper是mybatis需要的接口,如圖

public interface PersonMapper {
    @Select(value = "SELECT * FROM person where id = #{id} " )
    Person getPerson(Person person);
}

Service是服務(wù)類

@Service
public class PersonServiceImpl implements PersonService{
    private final PersonMapper personMapper;

    public PersonServiceImpl(PersonMapper personMapper) {
        this.personMapper = personMapper;
    }

    public Person getPerson(Person person) {
        return personMapper.getPerson(person);
    }
}

Main測試類燕锥,獲取context子刮,取得服務(wù)類威酒,然后調(diào)用getPerson方法

public class Main {
    public static void main(String[] args) {
     ApplicationContext context = new ClassPathXmlApplicationContext("com/ly1/ly-config-context.xml");
      //  ApplicationContext context=new AnnotationConfigApplicationContext(LyConfig2.class);
        PersonServiceImpl personService = context.getBean(PersonServiceImpl.class);
        Person person = new Person();
        person.setId("1");
        long startTime = System.currentTimeMillis();
        Person person1 = personService.getPerson(person);
        long endTime = System.currentTimeMillis();
        //第一次查詢比較耗時 2337毫秒
        System.out.println("花費了[" + (endTime - startTime) + "]毫秒");
        System.out.println(person1);
        person.setId("2");
        startTime = System.currentTimeMillis();
        Person person2 = personService.getPerson(person);
        endTime = System.currentTimeMillis();
        //4毫秒
        System.out.println("花費了[" + (endTime - startTime) + "]毫秒");
        System.out.println(person2);
    }
}

使用java注解配置(相比上面去掉了spring-context.xml文件)

如圖


image.png

service,mapper挺峡,和entity包內(nèi)的文件沒有任何變動
先看Main測試類,相比上述的代碼葵孤,僅僅是改變了context獲取方式而已

     //   ApplicationContext context = new ClassPathXmlApplicationContext("com/ly1/ly-config-context.xml");
         ApplicationContext context=new AnnotationConfigApplicationContext(LyConfig2.class);

主要看Config.java類,有三種寫法

第一種寫法

與xml配置幾乎一致橱赠,沒有變動尤仍,只不過使用形式不同


/**
 * 這里使用注解,基本和xml一致
 */
@Configuration
@ComponentScan(basePackages = "com.ly1.service")
public class LyConfig {
    @Bean
    public MapperFactoryBean<PersonMapper> personMapper() throws Exception {
        MapperFactoryBean<PersonMapper> factoryBean=new MapperFactoryBean<PersonMapper>();
        factoryBean.setSqlSessionFactory(sqlSessionFactory());
        factoryBean.setMapperInterface(PersonMapper.class);
        return factoryBean;
    }
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        return sqlSessionFactoryBean.getObject();
    }
    @Bean
    public BasicDataSource dataSource(){
        BasicDataSource dataSource=new BasicDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/test1");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("test.lwm");
        return dataSource;
    }
}

第二種寫法

直接使用MapperScan,不需要進行配置狭姨,會自動掃描



@Configuration
@ComponentScan(basePackages = {"com.ly1.service","com.ly1.mapper"})
@MapperScan(value = {"com.ly1.mapper"})
public class LyConfig1 {
    /*@Bean
    public MapperFactoryBean<PersonMapper> personMapper() throws Exception {
        MapperFactoryBean<PersonMapper> factoryBean=new MapperFactoryBean<PersonMapper>();
        factoryBean.setSqlSessionFactory(sqlSessionFactory());
        factoryBean.setMapperInterface(PersonMapper.class);
        return factoryBean;
    }*/
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        return sqlSessionFactoryBean.getObject();
    }
    /*@Bean
    public PersonMapper personMapper() throws Exception {
        SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(sqlSessionFactory());
        final PersonMapper personMapper = sqlSessionTemplate.getMapper(PersonMapper.class);
        return personMapper;
    }*/
    @Bean
    public BasicDataSource dataSource(){
        BasicDataSource dataSource=new BasicDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/test1");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("test.lwm");
        return dataSource;
    }
}

第三種寫法


@Configuration
@ComponentScan(basePackages = {"com.ly1.service","com.ly1.mapper"})
//@MapperScan("com.ly1.mapper")
public class LyConfig2 {
    /*
    //方法a1 使用該方法則不需要像下面的方法需要提前注冊Mapper類
    //the mapper is not autoregistered so it must appear in the mybatis-config or it can be registered by calling config.addMapper()
    @Bean
    public MapperFactoryBean<PersonMapper> personMapper() throws Exception {
        MapperFactoryBean<PersonMapper> factoryBean=new MapperFactoryBean<PersonMapper>();
        factoryBean.setSqlSessionFactory(sqlSessionFactory());
        factoryBean.setMapperInterface(PersonMapper.class);
        return factoryBean;
    }*/
    //方法a2
    @Bean
    public PersonMapper personMapper() throws Exception {
        SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(sqlSessionFactory());
        final PersonMapper personMapper = sqlSessionTemplate.getMapper(PersonMapper.class);
        return personMapper;
    }
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        //如果使用上面的方法宰啦,拿sqlSessionTemplate.getMapper,必須先注冊Mapper類,如下兩種方法
        /*
        //方法b1
        org.apache.ibatis.session.Configuration configuration=new org.apache.ibatis.session.Configuration();
        configuration.addMapper(PersonMapper.class);
        sqlSessionFactoryBean.setConfiguration(configuration);*/
        //方法2
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("com/ly1/ly-config-mybatis.xml"));
        return sqlSessionFactoryBean.getObject();
    }
    @Bean
    public BasicDataSource dataSource(){
        BasicDataSource dataSource=new BasicDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/test1");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("test.lwm");
        return dataSource;
    }
}

注意鲤嫡,這里手動設(shè)置了personMapper類,獲取之前是需要先加進去的绑莺,添加方法為注釋掉的方法b1和沒有主食的方法b2暖眼,

方法b1

org.apache.ibatis.session.Configuration configuration=new org.apache.ibatis.session.Configuration();
        configuration.addMapper(PersonMapper.class);
        sqlSessionFactoryBean.setConfiguration(configuration);

方法b2

 sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("com/ly1/ly-config-mybatis.xml"));

ly-config-mybatis.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>
    <mappers>
        <mapper class="com.ly1.mapper.PersonMapper" />
    </mappers>
</configuration>

其實也只是在config文件中添加了mapper

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市纺裁,隨后出現(xiàn)的幾起案子诫肠,更是在濱河造成了極大的恐慌,老刑警劉巖欺缘,帶你破解...
    沈念sama閱讀 212,599評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件栋豫,死亡現(xiàn)場離奇詭異,居然都是意外死亡谚殊,警方通過查閱死者的電腦和手機丧鸯,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,629評論 3 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來嫩絮,“玉大人丛肢,你說我怎么就攤上這事〗烁桑” “怎么了蜂怎?”我有些...
    開封第一講書人閱讀 158,084評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長置尔。 經(jīng)常有香客問我杠步,道長,這世上最難降的妖魔是什么榜轿? 我笑而不...
    開封第一講書人閱讀 56,708評論 1 284
  • 正文 為了忘掉前任幽歼,我火速辦了婚禮,結(jié)果婚禮上谬盐,老公的妹妹穿的比我還像新娘甸私。我一直安慰自己,他們只是感情好设褐,可當(dāng)我...
    茶點故事閱讀 65,813評論 6 386
  • 文/花漫 我一把揭開白布颠蕴。 她就那樣靜靜地躺著泣刹,像睡著了一般助析。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上椅您,一...
    開封第一講書人閱讀 50,021評論 1 291
  • 那天外冀,我揣著相機與錄音,去河邊找鬼掀泳。 笑死雪隧,一個胖子當(dāng)著我的面吹牛西轩,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播脑沿,決...
    沈念sama閱讀 39,120評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼藕畔,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了庄拇?” 一聲冷哼從身側(cè)響起注服,我...
    開封第一講書人閱讀 37,866評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎措近,沒想到半個月后溶弟,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,308評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡瞭郑,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,633評論 2 327
  • 正文 我和宋清朗相戀三年辜御,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片屈张。...
    茶點故事閱讀 38,768評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡擒权,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出阁谆,到底是詐尸還是另有隱情菜拓,我是刑警寧澤,帶...
    沈念sama閱讀 34,461評論 4 333
  • 正文 年R本政府宣布笛厦,位于F島的核電站纳鼎,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏裳凸。R本人自食惡果不足惜贱鄙,卻給世界環(huán)境...
    茶點故事閱讀 40,094評論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望姨谷。 院中可真熱鬧逗宁,春花似錦、人聲如沸梦湘。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,850評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽捌议。三九已至哼拔,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間瓣颅,已是汗流浹背倦逐。 一陣腳步聲響...
    開封第一講書人閱讀 32,082評論 1 267
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留宫补,地道東北人檬姥。 一個月前我還...
    沈念sama閱讀 46,571評論 2 362
  • 正文 我出身青樓曾我,卻偏偏與公主長得像,于是被迫代替她去往敵國和親健民。 傳聞我的和親對象是個殘疾皇子抒巢,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,666評論 2 350

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