本文不再叙述基础知识,直接列举主要步骤,基础知识可查看官方文档。
一个可以运行通过的mybatis简介小例子:
http://www.cnblogs.com/magialmoon/archive/2013/10/30/3397828.html
1.前期准备准备 jdbc包 mybatis jar包 configuration.xml user.xml
configuration.xml原始内容如下
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Copyright 2009-2016 the original author or authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="useGeneratedKeys" value="false"/>
<setting name="useColumnLabel" value="true"/>
</settings>
<typeAliases>
<typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/>//创建别名
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value=""/>
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:complexprop"/>
<property name="username" value="sa"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/apache/ibatis/submitted/complex_property/User.xml"/>
</mappers>
</configuration>
user.xml内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2009-2016 the original author or authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="User">
<resultMap type="UserAlias" id="UserResult">//type是bean的位置
<id column="id" jdbcType="INTEGER" property="id"/>//数据库中的column id 对应着 UserAlias中的 property id
<result column="username" jdbcType="VARCHAR" property="username"/>
<result column="password" jdbcType="VARCHAR" property="password.encrypted"/>
<result column="administrator" jdbcType="BOOLEAN" property="administrator"/>
</resultMap>
<select id="find" parameterType="long" resultMap="UserResult">
SELECT * FROM user WHERE id = #{id:INTEGER}
</select>
<select id="version" parameterType="long" resultType="int">
SELECT version FROM user WHERE id = #{id,jdbcType=INTEGER}
</select>
<delete id="delete" parameterType="UserAlias">
DELETE FROM user WHERE id = #{id:INTEGER}
</delete>
<insert id="insert" parameterType="UserAlias" useGeneratedKeys="false">
INSERT INTO user
( id,
username,
password,
administrator
)
VALUES
( #{id},
#{username,jdbcType=VARCHAR},
#{password.encrypted:VARCHAR},
#{administrator,jdbcType=BOOLEAN}
)
</insert>
<update id="update" parameterType="UserAlias">
UPDATE user SET
username = #{username,jdbcType=VARCHAR},
password = #{password.encrypted,jdbcType=VARCHAR},
administrator = #{administrator,jdbcType=BOOLEAN}
WHERE
id = #{id,jdbcType=INTEGER}
</update>
<!-- Unique constraint check -->
<select id="isUniqueUsername" parameterType="map" resultType="boolean">
SELECT (count(*) = 0)
FROM user
WHERE ((#{userId,jdbcType=BIGINT} IS NOT NULL AND id != #{userId,jdbcType=BIGINT}) OR #{userId,jdbcType=BIGINT} IS
NULL) <!-- other than me -->
AND (username = #{username,jdbcType=VARCHAR})
</select>
</mapper>
2.创建 一个(如mapperuser)接口 一个bean类(如user)类,一个工具类(如 MyBatisUtil)。 配置两个配置文件,有以下注意的地方 * configuration.xml要mappers中引入user.xml 。* user.xml中namespace必须是UserMapper接口,各段语句id必须和接口中方法名一致, sql语句中传入的参数只能是一个,所以传入类(如user),sql结尾不能加分号。
user.xml中的语句示例:
<insert id="insertUser" parameterType="User">
insert into user(name,age) values(#{name},#{age})
<!-- 这里sql结尾不能加分号,否则报“ORA-00911”的错误 -->
</insert>
<!-- 这里的id必须和UserMapper接口中的接口方法名相同 -->
<select id="getUser" resultType="User" parameterType="java.lang.String">
select * from user where name=#{name}
</select>
3.工具类格式基本固定,有如下函数
public static SqlSession getSqlSession() throws IOException{
Reader reader=Resources.getResourceAsReader("Configuration.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession=sqlSessionFactory.openSession();
return sqlSession;
}
4.在测试类中使用工具类进行数据库操作
public static void main(String[] args) {
SqlSession sqlsession=null;
try {
sqlsession=MyBatisUtil.getSqlSession();
/*用sqlsession进行的操作。*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(sqlsession!=null)
{
sqlsession.close();
}
}
5.可进行操作举例:
(1)
UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = new User("lisi", new Integer(25)); userMapper.insertUser(user); sqlSession.commit();
整体关系 工具类<-configuration.xml<-user.xml<-接口 使用时用工具类获得sqlsession,sqlsession获得接口,接口执行user.xml中对应的方法。