mapper动态代理方式crud(Mybatis接口开发)
约定优于配置:
配置方式:
abc.xml
<name>projectName</name>
硬编码方式:
abc.xml
Configuration conf = new Configuration();
con.serName("ProjectName");
约定:默认值就是projectName
具体实现的步骤:
1.基础环境:myBatis.jar, conf.xml mapper.xml
------->约定的目标:省略掉statement,即根据约定可以直接定位出SQL语句
2.定义接口:接口中的方法必须遵行以下约定:
1.方法名和mapper.xml中标签的id值相同
2.方法的输入参数和mapper.xml文件中的parameterType类型一致
3.方法的返回值和mapper.xml文件中标签的resultType类型一致
–除了以上约定,要实现接口中的方法 和 Mapper.xml中SQL标签一一对应,还需以下一点:
– namespace的值, 就是接口的全类名(接口–mapper.xml一一对应)
匹配的过程:(约定的过程)
1.根据 接口名 找到mapper.xml文件(根据的是namespace=接口全类名)
2.根据 接口的方法名 找到mapper.xml文件中的SQL标签(方法名=SQL标签Id)
以上两点可以保证:当我们调用接口中的方法时.程序可以自动定位到 某一个 mapper.xml文件中的sql标签
习惯:将接口 和 mapper.xml文件放在同一个包下
优化: 可以将配置信息 单独放入 db.properties文件中,然后再动态引入
• SqlSession 的实例不是线程安全的,因此是不能 被共享的。
• SqlSession每次使用完成后需要正确关闭,这个 关闭操作是必须的
• SqlSession可以直接调用方法的id进行数据库操 作,但是我们一般还是推荐使用SqlSession获取 到Dao接口的代理类,执行代理对象的方法,可 以更安全的进行类型检查操作
mapper
<?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">
<!--namespace:该mapper.xml映射文件的唯一标识 -->
<mapper namespace="mapper.PersonMapper">
<select id="queryPersonById" resultType="Person" parameterType="int">
SELECT * FROM person WHERE id = #{id}
</select>
<insert id="PersonInsert" parameterType="Person">
INSERT INTO person(name,age) VALUES(#{name},#{age})
</insert>
<delete id="PersonDelete" parameterType="int">
DELETE FROM person WHERE id = #{id}
</delete>
<update id="PersonUpdate" parameterType="Person">
UPDATE person SET name=#{name},age=#{age} WHERE id = #{id}
</update>
<select id="queryAll" resultType="Person">
SELECT * FROM person WHERE id > 0
</select>
</mapper>
Dao
//操作mybatis的接口
public interface PersonMapper {
/*1.方法名和mapper.xml中标签的id值相同
2.方法的输入参数和mapper.xml文件中的parameterType类型一致
3.方法的返回值和mapper.xml文件中标签的resultType类型一致
*/
public Person queryPersonById(int id);
public void PersonInsert(Person person);
public void PersonDelete(int id);
public void PersonUpdate(Person person);
public List<Person> queryAll();
}
java
使用SqlSession获取映射器进行操作
@Test
public void test() throws IOException {
Reader reader = Resources.getResourceAsReader("conf.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = build.openSession();
//使用SqlSession获取映射器进行操作
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
Person result = mapper.queryPersonById(2);
System.out.println(result);
mapper.PersonDelete(2);
mapper.PersonInsert(new Person("fg",19));
mapper.PersonUpdate(new Person(3,"max",18));
List<Person> people = mapper.queryAll();
System.out.println(people);
}