MyBatis mapping类基本用法
有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
定义mapping类
MyBatis 有两种定义查询结果到 Java 类的映射关系的方式,一种是通过xml文件定义,一种是通过Java annonation 定义,这里使用第二种方法。
现在我们有一张mysql的表定义如下:
CREATE TABLE `MY_BATIS_TEST` ( `id` varchar(255) NOT NULL DEFAULT '', `url` varchar(255) DEFAULT NULL )
首先定义table一条数据在Java中对应的class
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); }
初始化并注册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中查询数据
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(); }
以上就是MyBatis mapping类基本用法的详细内容,更多关于MyBatis mapping类的资料请关注脚本之家其它相关文章!
相关文章
Spring Data Redis切换底层Jedis和Lettuce实现源码解析
这篇文章主要为大家介绍了Spring Data Redis切换底层Jedis和Lettuce实现方法源码解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-11-11Spingboot JPA CriteriaBuilder 如何获取指定字段
这篇文章 主要介绍了Spingboot JPA CriteriaBuilder 如何获取指定字段,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-12-12SpringBoot详细讲解异步任务如何获取HttpServletRequest
在使用框架日常开发中需要在controller中进行一些异步操作减少请求时间,但是发现在使用@Anysc注解后会出现Request对象无法获取的情况,本文就此情况给出完整的解决方案2022-04-04Java ArrayList遍历foreach与iterator时remove的区别
这篇文章主要介绍了Java ArrayList遍历foreach与iterator时remove的区别,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下2022-07-07详解Spring boot使用Redis集群替换mybatis二级缓存
本篇文章主要介绍了详解Spring boot使用Redis集群替换mybatis二级缓存,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-05-05
最新评论