首先要有jar包:mybatis-3.2.8.jar,以及连接数据库的jar包,根据连接数据库的不同而选择。
数据库中建表,项目中建model:User.java,同时建立这个User 的映射文件 User.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="com.gch.UserMapper">
<select id="selectUserByID"parameterType="int" resultType="User">
select * from `user` where id =#{id}
</select>
< /mapper>
设置mybatis配置文件:Configuration.xml
< ?xml version="1.0" encoding="UTF-8" ?>
< !DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
< configuration>
<!--别名-->
<typeAliases>
<typeAlias alias="User"type="com.gch.model.User"/>
</typeAliases>
<environments default="development">
<environmentid="development">
<transactionManagertype="JDBC"/>
<dataSource type="POOLED">
<propertyname="driver" value="com.mysql.jdbc.Driver"/>
<propertyname="url" value="jdbc:mysql://1192.168.254.128:3306/mybatis" />
<propertyname="username" value="root"/>
<propertyname="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapperresource="com/gch/model/User.xml"/>
</mappers>
< /configuration>
测试的主要代码:
Reader reader = Resources.getResourceAsReader("Configuration.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session =sqlSessionFactory.openSession();
User user = (User)session.selectOne("com.gch.models.UserMapper.selectUserByID",1);
System.out.println(user.getUserAddress());
=========================================================
以上的代码,简单的实现mybatis操作数据,但离实际的工作开发有点远
=========================================================
使用接口方式:
建立接口类 IUserOperation.java
public interface IUserOperation {
public User selectUserByID(int id);
}
修改<mapper namespace="com.gch.dao.inter.IUserOperation">
请注意,这里面有一个方法名 selectUserByID 必须与 User.xml 里面配置的 select 的 id 对应( <select id="selectUserByID" )测试的主要代码:
IUserOperationuserOperation=session.getMapper(IUserOperation.class);
=================================================================