MyBatis 有兩種定義查詢結果到 Java 類的映射關係的方式,一種是經過xml文件定義,一種是經過Java annonation 定義,這裏使用第二種方法。 如今咱們有一張mysql的表定義以下:java
CREATE TABLE `MY_BATIS_TEST` ( `id` varchar(255) NOT NULL DEFAULT '', `url` varchar(255) DEFAULT NULL )
首先定義table一條數據在Java中對應的classmysql
public class Redord { public String url; }
定義sql查詢到Java class 結果集合的映射:sql
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); }
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);
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的生命週期中只建立一次,SqlSession須要在每次執行sql的函數中建立一次而且使用後須要進行關閉:安全
SqlSession session = sqlSessionFactory.openSession(); try { // do work } finally { session.close(); }