Mybatis的Dao层实现:代理开发方式
代理开发方式只要写好接口就行了,不需要像传统实现方式那样自己去实现接口,由Mybatis 框架根据接口定义创建接口的动态代理对象
Mapper 接口开发需要遵循以下规范:
1) Mapper.xml文件中的namespace与mapper接口的全限定名相同
2) Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
3) Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同
4) Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同
编写映射文件mapper.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.dao.UserMapper">
<!-- 查询操作-->
<select id="findAll" resultType="com.domain.User">
select * from User
</select>
<!-- 插入操作-->
<insert id="add" parameterType="com.domain.User">
insert into User values (#{id},#{username},#{password})
</insert>
<!-- 修改数据-->
<update id="update" parameterType="com.domain.User">
update User set password = #{password} where username=#{username}
</update>
<!-- 删除操作-->
<delete id="delete" parameterType="com.domain.User">
delete from User where username=#{username}
</delete>
</mapper>
编写核心文件
<?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>
<!-- 指定默认的环境名称-->
<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/one"/>
<property name="username" value="root"/>
<property name="password" value="admin123"/>
</dataSource>
</environment>
</environments>
<!-- 加载映射文件-->
<mappers>
<mapper resource="com/mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>
编写接口UserMapper
package com.dao;
import com.domain.User;
import java.util.List;
public interface UserMapper {
List<User> findAll();
}
测试
@Test
public void test2() throws IOException {
// 加载核心配置文件
InputStream resource = Resources.getResourceAsStream("sqlMapConfig.xml");
// 获得sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);
// 获得SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获得Mybatis框架生成的UserMapper接口实现类
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> list = userMapper.findAll();
System.out.println(list);
// 释放资源
sqlSession.close();
}