MyBatis基本使用(使用IDEA)
阿新 • • 發佈:2020-12-07
通過這個案例完成,對資料庫的查詢功能
一、基本使用方法
步驟一:建立一個新的介面在mapper資料夾下
public interface DemoMapper { //下面的方法就是Mybatis實現的查詢方法了 //不需要編寫實現類 @Select("select username from vrduser where id=1") public String hello(); }
步驟二:在MybatisConfig中配置類SqlSessionFactory
1.SqlSessionFactory類的作用:自動生成實現類
類上加了註解@MapperScan("cn.tedu.mapper")
表示指定SqlSessionFactory類要掃描並生成實現類的包
@PropertySource("classpath:jdbc.properties") @MapperScan("cn.tedu.mapper") public class MyBatisConfig { //SqlSessionFactory這個類時Mybatis中的一個重要的類 //它的功能非常強大,能根據介面中宣告的資訊,自動實現這個介面的實現類,並將這個實現類注入到Spring容器以便我們使用 @Bean public SqlSessionFactory sqlSessionFactory( DataSource dataSource)throws Exception { SqlSessionFactoryBean bean= new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } }
2.配置完畢,進行測試
public class Test{ AnnotationConfigApplicationContext ctx; @Before public void berfore(){ ctx= new AnnotationConfigApplicationContext(Mybaits_Config.class); System.out.println("測試開始"); } @Test public void TestFactory(){ SqlSessionFactory factory = ctx.getBean("sqlSessionFactory",SqlSessionFactory.class); System.out.println(factory); } //執行Mapper介面中的方法 @Test public void testUsernamme(){ DemoMapper mapper = ctx.getBean("demoMapper",DemoMapper.class); String name = mapper.hello(); System.out.println(name); } @After public void after(){ System.out.println("測試結束"); ctx.close(); } }
@TestTestFactory:所測試的是,檢視是否可以成功獲取SqlSessionFactory類配置成功
輸出:
測試開始
org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@7748410a
測試結束
@TesttestUsernamme:獲取介面DemoMapper中的方法並執行
輸出:
測試開始
admin
測試結束