Java+MyBatis+MySQL开发环境搭建流程详解
主要搭建过程
1.pom.xml文件中加入mybatis和数据库依赖,这里使用mysql:
<properties> <mybatis.version>3.2.3</mybatis.version> <mysql.version>5.1.26</mysql.version> <slf4j.api.version>1.7.5</slf4j.api.version> <testng.version>6.8.7</testng.version> </properties> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!--Databasedriver--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!--mybatis启动要加载log4j--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.api.version}</version> </dependency> <!--Test--> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>${testng.version}</version> </dependency> </dependencies>
2.在类路径下创建mybatis的配置文件Configuration.xml
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTDConfig3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases><!--别名--> <typeAliasalias="User"type="com.john.hbatis.model.User"/> </typeAliases> <environmentsdefault="development"> <environmentid="development"> <transactionManagertype="JDBC"/> <dataSourcetype="POOLED"><!--数据源--> <propertyname="driver"value="com.mysql.jdbc.Driver"/> <propertyname="url"value="jdbc:mysql://localhost:3306/hbatis"/> <propertyname="username"value="root"/> <propertyname="password"value="123456"/> </dataSource> </environment> </environments> <mappers><!--ORM映射文件--> <mapperresource="com/john/hbatis/model/User.xml"/> </mappers> </configuration>
3.执行创建数据库和表的sql:
--Createthedatabasenamed'hbatis'. --It'sOKtouse`,notOKtouse'or"surroundingthedatabasenametopreventitfrombeinginterpretedasakeywordifpossible. CREATEDATABASEIFNOTEXISTS`hbatis` DEFAULTCHARACTERSET=`UTF8`; --Createatablenamed'User' CREATETABLE`user`( `id`int(11)NOTNULLAUTO_INCREMENT, `name`varchar(50)DEFAULTNULL, `age`int(11)DEFAULTNULL, `address`varchar(200)DEFAULTNULL, PRIMARYKEY(`id`) )ENGINE=InnoDBAUTO_INCREMENT=2DEFAULTCHARSET=utf8; --Insertatestrecord InsertINTO`user`VALUES('1','john','120','hangzhou,westlake');
4.com.john.hbatis.model.User类:
publicclassUser{ privateintid; privateStringname; privateStringage; privateStringaddress; //Gettersandsettersareomitted //如果有带参数的构造器,编译器不会自动生成无参构造器。当查询需要返回对象时,ORM框架用反射来调用对象的无参构造函数,导致异常:java.lang.NoSuchMethodException:com.john.hbatis.model.User.<init>() //这时需要明确写出: publicUser(){ } publicUser(intid,Stringaddress){ this.id=id; this.address=address; } publicUser(Stringname,intage,Stringaddress){ this.name=name; this.age=age; this.address=address; } }
com/john/hbatis/model路径下的User.xml
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mappernamespace="com.john.hbatis.model.UserMapper"> <selectid="getUserById"parameterType="int"resultType="User"> select*from`user`whereid=#{id} </select> </mapper>
5.测试类:
publicclassMyBatisBasicTest{ privatestaticfinalLoggerlog=LoggerFactory.getLogger(MyBatisBasicTest.class); privatestaticSqlSessionFactorysqlSessionFactory; privatestaticReaderreader; @BeforeClass publicstaticvoidinitial(){ try{ reader=Resources.getResourceAsReader("Configuration.xml"); sqlSessionFactory=newSqlSessionFactoryBuilder().build(reader); }catch(IOExceptione){ log.error("Errorthrownwhilereadingtheconfiguration:{}",e); }finally{ if(reader!=null){ try{ reader.close(); }catch(IOExceptione){ log.error("Errorthrownwhileclosingthereader:{}",e); } } } } @Test publicvoidqueryTest(){ SqlSessionsession=sqlSessionFactory.openSession(); Useruser=(User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById",1); log.info("{}:{}",user.getName(),user.getAddress()); } }
以接口方式交互数据
上面的环境搭建是采用SqlSession的通用方法并强制转换的方式,存在着转换安全的问题:
Useruser=(User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById",1);
可以采用接口加sql语句的方式来解决,sql语句理解为是接口的实现:
1.新建接口类:
packagecom.john.hbatis.mapper; importcom.john.hbatis.model.User; publicinterfaceIUserMapper{ UsergetUserById(intid); }
2.修改User.xml文件,确保namespace属性值和接口的全限定名相同,且id属性值和接口方法名相同:
<mappernamespace="com.john.hbatis.mapper.IUserMapper"> <selectid="getUserById"
3.在MyBatisBasicTest类中添加测试方法:
@Test publicvoidqueryInInterfaceWayTest(){ SqlSessionsession=sqlSessionFactory.openSession(); IUserMappermapper=session.getMapper(IUserMapper.class);//如果namespace和接口全限定名不一致,报org.apache.ibatis.binding.BindingException:Typeinterfacecom..IUserMapperisnotknowntotheMapperRegistry异常。 Useruser=mapper.getUserById(1); log.info("{}:{}",user.getName(),user.getAddress()); }
附:
上面的实现是把sql语句放在XML文件中,并通过一定的约束来保证接口能够在XML中找到对应的SQL语句;
还有一种方式是通过接口+注解SQL方式来交互数据:
1.新建接口类:
packagecom.john.hbatis.mapper; importorg.apache.ibatis.annotations.Select; importcom.john.hbatis.model.User; publicinterfaceIUserMapper2{ @Select({"select*from`user`whereid=#{id}"}) UsergetUserById(intid); }
2.在Configuration.xml文件中加入:
<mappers> <mapperclass="com.john.hbatis.mapper.IUserMapper2"/> </mappers>
或在初始化语句中加入:
sqlSessionFactory.getConfiguration().addMapper(IUserMapper2.class);
3.相应修改上面的测试方法:
IUserMapper2mapper=session.getMapper(IUserMapper2.class);