Java的MyBatis框架项目搭建与hellow world示例
新建项目(我使用的是maven项目)mybatis-study-01
一、加入mybatis与mysql-connector依赖包到pom文件
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>mybatis</groupId> <artifactId>mybatis-study-01</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>mybatis-01</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <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.27</version> </dependency> </dependencies> </project>
二、创建数据库mybatis-test
新建一张user表用于测试。建表sql如下:
CREATETABLE`user`( `id`int(11)NOTNULLauto_increment, `password`varchar(255)defaultNULL, `user_name`varchar(50)defaultNULL, `user_age`int(11)defaultNULL, `user_address`varchar(200)defaultNULL, PRIMARYKEY(`id`), UNIQUEKEY`userName`(`user_name`) )EN
插入一条数据
INSERTINTO`user`VALUES('1','123131','summer','100','shanghai,pudong');
三、在项目中编写pojo对象。
packagecom.zf.mybatis.pojo; publicclassUser{ privateintid; privateStringpassword; privateStringuserName; privateStringuserAge; privateStringuserAddress; publicintgetId(){ returnid; } publicvoidsetId(intid){ this.id=id; } publicStringgetUserName(){ returnuserName; } publicvoidsetUserName(StringuserName){ this.userName=userName; } publicStringgetUserAge(){ returnuserAge; } publicvoidsetUserAge(StringuserAge){ this.userAge=userAge; } publicStringgetUserAddress(){ returnuserAddress; } publicvoidsetUserAddress(StringuserAddress){ this.userAddress=userAddress; } publicStringgetPassword(){ returnpassword; } publicvoidsetPassword(Stringpassword){ this.password=password; } }
四、编写pojo对应的映射文件User.xml
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mappernamespace="com.zf.mybatis.pojo.UserMapper"> <!--使用sql标签可以将公共的sql提取出来复用--> <sqlid="queryFields"> id,password,user_nameasuserName,user_ageasuserAge,user_addressasuserAddress </sql> <selectid="selectByID"parameterType="int"resultType="User"> select <includerefid="queryFields"/> from`user`whereid=#{id} </select> <insertid="add"parameterType="User"useGeneratedKeys="true"keyProperty="id"> insertinto`user` (password,user_name,user_age,user_address) values(#{password},#{userName},#{userAge},#{userAddress}) </insert> <updateid="update"parameterType="User"> update`user` setpassword=#{password},user_name=#{userName},user_age=#{userAge},user_address=#{userAddress} whereid=#{id} </update> <deleteid="deleteById"parameterType="int"> deletefrom`user`whereid=#{id} </delete> </mapper>
注意:上面的namespace的值为com.zf.mybatis.pojo.UserMapper,可以自定义,UserMapper不是一个类,不需要存在的。
另外,mybatis会将从数据库查询出来的记录根据列名与pojo中的字段进行匹配,所以上面的user_name,user_age,user_address这几个字段都取了别名,跟pojo中的字段相对应。如果不起别名,查询出来的对象,这几个字段是没有值的。
五、编写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> <!--配置别名--> <typeAliases> <typeAliasalias="User"type="com.zf.mybatis.pojo.User"/> </typeAliases> <!--数据库配置信息--> <environmentsdefault="development"> <environmentid="development"> <transactionManagertype="JDBC"/> <dataSourcetype="POOLED"> <propertyname="driver"value="com.mysql.jdbc.Driver"/> <propertyname="url"value="jdbc:mysql://127.0.0.1:3306/mybatis-test"/> <propertyname="username"value="root"/> <propertyname="password"value="root"/> </dataSource> </environment> </environments> <!--映射文件--> <mappers> <mapperresource="conf/User.xml"/> </mappers> </configuration>
在该配置文件中配置了数据库的链接方式,以及注册所有的映射文件,还可以设置mybatis的一些参数。
现在就可以编写测试类了。来测试一下。
packagecom.zf.mybatis; importjava.io.IOException; importjava.io.Reader; importorg.apache.ibatis.io.Resources; importorg.apache.ibatis.session.SqlSession; importorg.apache.ibatis.session.SqlSessionFactory; importorg.apache.ibatis.session.SqlSessionFactoryBuilder; importorg.junit.Before; importorg.junit.Test; importcom.zf.mybatis.pojo.User; publicclassTestMyBatis{ privateSqlSessionFactorysqlSessionFactory; privateReaderreader; @Before publicvoidinit(){ try{ reader=Resources.getResourceAsReader("mybatis-config.xml"); sqlSessionFactory=newSqlSessionFactoryBuilder().build(reader); }catch(IOExceptione){ e.printStackTrace(); } } @Test publicvoidtestQueryUser(){ SqlSessionsession=sqlSessionFactory.openSession(); try{ Useruser=(User)session.selectOne("com.zf.mybatis.pojo.UserMapper.selectByID",1); System.out.println(user.getUserAddress()); System.out.println(user.getUserName()); }finally{ session.close(); } } @Test publicvoidtestInsertUser(){ SqlSessionsession=sqlSessionFactory.openSession(); try{ Useruser=newUser(); user.setUserName("abcde"); user.setUserAge(15); user.setUserAddress("hangzhou/zhejiang"); user.setPassword("123456"); //返回值是记录条数 intresultCount=session.insert("com.zf.mybatis.pojo.UserMapper.add",user); session.commit(); System.out.printf("userID:%d,总记录条数:%d",user.getId(),resultCount);//获取插入对象的id }finally{ session.close(); } } @Test publicvoidtestUpdateUser(){ SqlSessionsession=sqlSessionFactory.openSession(); try{ Useruser=newUser(); user.setId(5); user.setUserName("updateName"); user.setUserAge(101); user.setUserAddress("shenzhen/guangdong"); user.setPassword("000000"); //返回值是修改条数 intupdateCount=session.update("com.zf.mybatis.pojo.UserMapper.update",user); session.commit(); System.out.printf("修改条数:%d",updateCount); }finally{ session.close(); } } @Test publicvoidtestDelete(){ SqlSessionsession=sqlSessionFactory.openSession(); try{ //返回值是删除条数 intdeleteCount=session.update("com.zf.mybatis.pojo.UserMapper.deleteById",4); session.commit(); System.out.printf("删除条数:%d",deleteCount); }finally{ session.close(); } } }
运行testQueryUser结果如下:
shanghai,pudong summer
到此,一个mybatis的helloworld类型的小程序就出来了。
PS:MyBaits配置文件报错解决
Mybaits的配置文件校验很诡异,节点的位置还有要求
如下,会报错:
Thecontentofelementtype"configuration"mustmatch"(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,plugins?,environments?,mappers?)". <?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTDConfig3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environmentsdefault="development"> <environmentid="development"> <transactionManagertype="JDBC"/> <dataSourcetype="POOLED"> <propertyname="driver"value="oracle.jdbc.driver.OracleDriver"/> <propertyname="url"value="jdbc:oracle:thin:@xx:1521:xx"/> <propertyname="username"value="ireport"/> <propertyname="password"value="xxxx"/> </dataSource> </environment> </environments> <typeAliases> <typeAliastype="com.ice.stat.online.model.EventFlag"alias="EventFlag"/> </typeAliases> <mappers> <mapperresource="com/ice/stat/online/model/hbm/EventFlagMapper.xml"/> </mappers> </configuration>
把typeAliases放到最上面就好了说:
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTDConfig3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <typeAliastype="com.ice.stat.online.model.EventFlag"alias="EventFlag"/> </typeAliases> <environmentsdefault="development"> <environmentid="development"> <transactionManagertype="JDBC"/> <dataSourcetype="POOLED"> <propertyname="driver"value="oracle.jdbc.driver.OracleDriver"/> <propertyname="url"value="jdbc:oracle:thin:@xx:1521:xx"/> <propertyname="username"value="ireport"/> <propertyname="password"value="xxxx"/> </dataSource> </environment> </environments> <mappers> <mapperresource="com/ice/stat/online/model/hbm/EventFlagMapper.xml"/> </mappers> </configuration>