Mybatis是一个持久层框架,支持sql查询、存储过程和高级映射。
- 基本使用
先看一下我的项目结构
也就是比一般项目多了一个resource文件夹,用来放mybatis的配置,以及DAO配置的,如何导入相关的包。一个mybatis包,一个jdbc包,我这里用了maven来导包,当然你也可以新建一个lib文件放入相关包,并add进项目。这里注意一下resource文件夹设置为source root。
下面就写代码了。
首先Mybatis-config文件配置数据源相关及所有的数据映射文件。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--当返回的所有列都是空的时候,mybatis默认返回null-->
<settings>
<setting name="returnInstanceForEmptyRow" value="true"/>
</settings>
<!--设置别名。设置之后,Dao文件可以不用lhp.Student而用Student-->
<!--<typeAliases>-->
<!--<typeAlias type="lhp.Student" alias="Student"/>-->
<!--</typeAliases>-->
<!--环境配置-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<!--配置数据源-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root" />
<property name="password" value="" />
</dataSource>
</environment>
</environments>
<!--数据映射的Dao文件-->
<mappers>
<mapper resource="StudentDao.xml"/>
</mappers>
</configuration>
StudentDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="lhp">
<!--<mapper namespace="lhp.StudentMapper"> 如果为接口映射方式,则namespace为那个映射接口-->
<!--id与方法名对应
resultType:结果类型为类的时候记得加包名
parameterType:参数类型-->
<!--select-->
<select id="getStudentById" parameterType="int" resultType="lhp.Student">
select * from