MyBatis 有两种定义查询结果到 Java 类的映射关系的方式,一种是经过xml文件定义,一种是经过Java annonation 定义,这里使用第二种方法。
如今咱们有一张mysql的表定义以下:mysql
CREATE TABLE `MY_BATIS_TEST` ( `id` varchar(255) NOT NULL DEFAULT '', `url` varchar(255) DEFAULT NULL )
首先定义table一条数据在Java中对应的classsql
public class Redord { public String url; }
定义sql查询到Java class 结果集合的映射:安全
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的函数中建立一次而且使用后须要进行关闭:session
SqlSession session = sqlSessionFactory.openSession(); try { // do work } finally { session.close(); }