可以在https://github.com/mybatis/mybatis-3/releases下载mybatis的jar包和Source code。
首先找到核心配置文件Configuration.xml,路径为Source code下src\test\java\org\apache\ibatis\submitted\complex_property\Configuration.xml。在project中新建Configuration.xml,将其拷贝进去,在这个文件中自动加载驱动,建立连接。先只保留部分,其余注释掉。
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value=""/>
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/student"/>
<property name="username" value="root"/>
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="sqlmap/User.xml"/>
</mappers>
</configuration>
那么读核心配置文件的代码应该写在哪里呢?
Dao层的需求是:(1)对象能和数据库交互;(2)能够执行SQL语句
这里的对象就由mybatis提供,即SqlSession对象。
SqlSession对象有以下几个作用:向SQL语句传入参数,执行SQL语句,获取SQL语句结果,事务控制。
如何获得SqlSession对象?
单独抽出一层DBConnection层,用来专门访问数据库,专门获取SqlSession对象。
public class DBConnection {
public SqlSession getSqlSession() {
try {
Reader reader = Resources.getResourceAsReader("mybatis/Configuration.xml");//通过Configuration.xml文件获取数据库连接相关信息
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);//通过配置信息构建SqlSessionFactory
return sqlSessionFactory.openSession();//通过SqlSessionFactory打开数据库对话
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
SQL的基本配置:
同样地,在Source code的src\test\java\org\apache\ibatis\submitted\complex_property下找到User.xml。在project中新建User.xml,将其拷贝进去。例如:
<mapper namespace="User"> //设置名字空间,防止不同配置文件中出现同名id
<resultMap id="User" type="bean.User">
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="username" jdbcType="VARCHAR" property="username"/>
<result column="passsword" jdbcType="VARCHAR" property="password"/>
<result column="age" jdbcType="INTEGER" property="age"/>
<result column="gmt_modified" jdbcType="TIMESTAMP" property="gmtModified"/>
<result column="gmt_create" jdbcType="TIMESTAMP" property="gmtCreate"/>
</resultMap>
<select id="listAllUser" resultMap="User">
SELECT * FROM user
</select>
其中,column对应的是数据库中字段的名字,property代表Java代码中定义的变量名称。
如何调用User.xml文件呢?Configuration.xml文件之所以称为核心配置文件,是因为在其中可以配置其他的xml文件,如下:
在Configuration.xml文件中添加
<mappers>
<mapper resource="sqlmap/User.xml"/>
</mappers>
至此,便可以运行SQL语句了。
例如:
public class UserDaoImpl implements UserDao{
private DBConnection dbConnection = new DBConnection();
public List<User> listAllUser() {
SqlSession sqlSession = dbConnection.getSqlSession();
List<User> userList = sqlSession.selectList("User.listAllUser");//参数中User对应User.xml中的名字空间,listAllUser对应<select id="listAllUser" resultMap="User">
sqlSession.commit();
return userList;
}
}