MyBatis mapping類基本用法
有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
定義mapping類
MyBatis 有兩種定義查詢結(jié)果到 Java 類的映射關(guān)系的方式,一種是通過xml文件定義,一種是通過Java annonation 定義,這里使用第二種方法。
現(xiàn)在我們有一張mysql的表定義如下:
CREATE TABLE `MY_BATIS_TEST` ( `id` varchar(255) NOT NULL DEFAULT '', `url` varchar(255) DEFAULT NULL )
首先定義table一條數(shù)據(jù)在Java中對應的class
public class Redord { public String url; }
定義sql查詢到Java class 結(jié)果集合的映射:
public interface SimpleMapper { @Select("select url from testdb.MY_BATIS_TEST limit 1;") Redord selectOneRecord(); @Select("select url from testdb.MY_BATIS_TEST;") Set<Record> selectRecords(); @Select("select url from testdb.MY_BATIS_TEST where id=#{id};") Record selectRecordByID(int id); }
初始化并注冊mapping類
Properties properties = new Properties(); properties.setProperty("driver", "com.mysql.jdbc.Driver"); properties.setProperty("url", "jdbc:mysql://127.0.0.1:3306/testdb"); properties.setProperty("username", "the_user_name"); properties.setProperty("password", "the_password"); PooledDataSourceFactory pooledDataSourceFactory = new PooledDataSourceFactory(); pooledDataSourceFactory.setProperties(properties); DataSource dataSource = pooledDataSourceFactory.getDataSource(); Environment environment = new Environment("development", new JdbcTransactionFactory(), dataSource); Configuration configuration = new Configuration(environment); configuration.addMapper(SimpleMapper.class); //注冊mapping類 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
從mysql中查詢數(shù)據(jù)
SqlSession session = sqlSessionFactory.openSession(); try{ PluginMapper mapper = session.getMapper(PluginMapper.class); Plugin pl = mapper.selectPluginsByID(1000); System.out.println(pl.url); } finally { session.close(); }
全局唯一以及線程安全
SqlSessionFactory 可以在整個app的生命周期中只創(chuàng)建一次,SqlSession需要在每次執(zhí)行sql的函數(shù)中創(chuàng)建一次并且使用后需要進行關(guān)閉:
SqlSession session = sqlSessionFactory.openSession(); try { // do work } finally { session.close(); }
以上就是MyBatis mapping類基本用法的詳細內(nèi)容,更多關(guān)于MyBatis mapping類的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
java如何通過FileOutputStream字節(jié)流向文件中寫數(shù)據(jù)
這篇文章主要介紹了java如何通過FileOutputStream字節(jié)流向文件中寫數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12IDEA?服務器熱部署圖文詳解(On?Update?action/On?frame?deactivation)
這篇文章主要介紹了IDEA?服務器熱部署詳解(On?Update?action/On?frame?deactivation),本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03C/C++中的struct結(jié)構(gòu)體詳細解讀
這篇文章主要介紹了C/C++中的struct結(jié)構(gòu)體詳細解讀,結(jié)構(gòu)體是由一批數(shù)據(jù)組合而成的結(jié)構(gòu)型數(shù)據(jù),組成結(jié)構(gòu)型數(shù)據(jù)的每個數(shù)據(jù)稱為結(jié)構(gòu)型數(shù)據(jù)的“成員”,其描述了一塊內(nèi)存區(qū)間的大小及意義,需要的朋友可以參考下2023-10-10Java設計模式之責任鏈模式(Chain of Responsibility模式)介紹
這篇文章主要介紹了Java設計模式之責任鏈模式(Chain of Responsibility模式)介紹,本文講解了如何使用責任鏈模式,并給出了4種使用實例,需要的朋友可以參考下2015-03-03