Mybatis的详细使用教程
Mybatis所需要的jar包:
需要引用两个jar包,一个是mybatis,另一个是MySQL-connector-Java,如果是maven工程的话,pom里如下添加依赖就可以了。
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version> </dependency>
数据准备:
在MySQL中造点数据进行测试用:
CREATEDATABASEmybatis_test; CREATETABLEuser ( ageINTEGERNOTNULL, nameVARCHAR(64)NOTNULLDEFAULT'' ); insertuservalues(18,'zhanjindong'); insertuservalues(20,'zhangsan');
配置文件:
需要两类配置文件,一类是MyBatis的配置文件mybatis-config.xml,示例中是一个很简单配置,详细的配置网上有很多说明。
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEconfiguration PUBLIC"-//mybatis.org//DTDConfig3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!--changesfromthedefaultsfortesting--> <settingname="cacheEnabled"value="false"/> <settingname="useGeneratedKeys"value="true"/> <settingname="defaultExecutorType"value="REUSE"/> </settings> <typeAliases> <typeAliasalias="User"type="test.mybatis.User"/> </typeAliases> <environmentsdefault="development"> <environmentid="development"> <transactionManagertype="jdbc"/> <dataSourcetype="POOLED"> <propertyname="driver"value="com.mysql.jdbc.Driver"/> <propertyname="url"value="jdbc:mysql://192.168.71.38:3306/mybatis_test"/> <propertyname="username"value="root"/> <propertyname="password"value="123456"/> </dataSource> </environment> </environments> <mappers> <mapperresource="mappers/UserMapper.xml"/> </mappers> </configuration>
另一类是数据访问接口映射文件:示例中是UserMapper.xml。这个文件一般放在src/main/resource下面或子目录下mybatis就可以找到了,在mybatis-config.xml中由mappers/mapper节点的resource指定。
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEmapper PUBLIC"-//mybatis.org//DTDMapper3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mappernamespace="test.mybatis.UserMapper"> <!--这里namespace必须是UserMapper接口的路径”--> <insertid="insertUser"parameterType="User"> insertintouser(name,age)values(#{name},#{age}) <!--这里sql结尾不能加分号,否则报“ORA-00911”的错误--> </insert> <!--这里的id必须和UserMapper接口中的接口方法名相同--> <selectid="getUser"resultType="User"parameterType="java.lang.String"> select*fromuserwherename=#{name} </select> </mapper>
对应这个映射文件就是test.mybatis这个命名空间下的UserMapper这个接口,只是定义了访问数据表的接口:
packagetest.mybatis; publicinterfaceUserMapper{ publicvoidinsertUser(Useruser); publicUsergetUser(Stringname); }
需要一个POJO:User.java
packagetest.mybatis; publicclassUser{ privateStringname; privateIntegerage; publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicIntegergetAge(){ returnage; } publicvoidsetAge(Integerage){ this.age=age; } publicUser(Stringname,Integerage){ super(); this.name=name; this.age=age; } publicUser(){ super(); } }
测试:
通过MyBatis操作数据库用到的是一个叫SqlSession的类,这个类是通过SqlSessionFactory产生的,一般建议在全局维护一个SqlSessionFactory就可以了。
TestMyBatis.java packagetest.mybatis; importjava.io.IOException; importjava.io.Reader; importorg.apache.ibatis.io.Resources; importorg.apache.ibatis.session.SqlSessionFactory; importorg.apache.ibatis.session.SqlSessionFactoryBuilder; publicclassMyBatisUtil{ privatefinalstaticSqlSessionFactorysqlSessionFactory; static{ Stringresource="mybatis-config.xml"; Readerreader=null; try{ reader=Resources.getResourceAsReader(resource); }catch(IOExceptione){ System.out.println(e.getMessage()); } sqlSessionFactory=newSqlSessionFactoryBuilder().build(reader); } publicstaticSqlSessionFactorygetSqlSessionFactory(){ returnsqlSessionFactory; } }
测试代码如下:
TestMyBatis.java packagetest.mybatis; importorg.apache.ibatis.session.SqlSession; importorg.apache.ibatis.session.SqlSessionFactory; publicclassTestMyBatis{ staticSqlSessionFactorysqlSessionFactory=null; static{ sqlSessionFactory=MyBatisUtil.getSqlSessionFactory(); } publicstaticvoidmain(String[]args){ testAdd(); getUser(); } publicstaticvoidtestAdd(){ SqlSessionsqlSession=sqlSessionFactory.openSession(); try{ UserMapperuserMapper=sqlSession.getMapper(UserMapper.class); Useruser=newUser("lisi",newInteger(25)); userMapper.insertUser(user); sqlSession.commit();//这里一定要提交,不然数据进不去数据库中 }finally{ sqlSession.close(); } } publicstaticvoidgetUser(){ SqlSessionsqlSession=sqlSessionFactory.openSession(); try{ UserMapperuserMapper=sqlSession.getMapper(UserMapper.class); Useruser=userMapper.getUser("zhangsan"); System.out.println("name:"+user.getName()+"|age:" +user.getAge()); }finally{ sqlSession.close(); } } }
1、mybatis会用log4j记录日志,但是开启debug模式貌似对性能影响非常厉害。
2、mybatis的查询缓存对性能的影响非常大,启用和不启用差距非常大
以上所述是小编给大家介绍的Mybatis的详细使用教程,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!