1、使用步骤:
1)读取配置文件
InputStream in = Resource.getResourceAsStream("配置文件.xml");
一般不使用绝对路径、相当于路径
一般加载配置文件:
a、使用类加载器,它只能读取类路径的配置文件
b、使用ServletContext对象的getRealPath()
2)创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
3)使用工程生产SqlSession对象
SqlSession session = factory.openSession();
4)使用SqlSession创建Dao接口的代理对象
StudentDao studentDao = session.getMapper(StudentDao.class);
5)使用代理对象执行方法
studentDao.sql方法();
6)关闭方法
session.close();
注意:
在使用mybatis基于注解:
把xxx.xml(映射配置文件mapper)移除,在dao接口的方法上使用@Select注解,并且指定SQL语句@Select("select * from table_name")
同时需要在坐标配置文件.xml中的mapper配置时,使用class属性指定dao的全限定类名将(不使用resource属性,使用class属性)
class="com.lxb.dao.IStudent"
dao实现类实现操作
方法类创建Session,再使用操作方法
2、自定义mybatis的分析
mybatis在使用代理dao的方式实现增删改查
两件事:
1)创建代理对象Session
2)在代理对象中调用selectList方法
解析配置文件:configuration(数据库配置,连接信息)、mapper(方法映射配置信息,映射信息)
实体类属性和表中的列名时一致的,可以把表的列名看成是实体类的属性名称
3、Mybatis的CURD操作
1)根据id查询student,返回一个用户
a、dao持久层的接口
public Student selectById(Integer id);
b、mapper
<select id=”selectById" parameterType="java.lang.Integer" resultType="com.lxb.domain.Student">
select * from student where id=#{id}
</select>
2)插入一条记录
a、dao持久层的接口
public int insertStudent(Student student);
b、mapper
<insert id="saveStudent" parameterType="com.lxb.domain.Student">
insert into student(id,name,age) values(#{id},#{name},#{age})
</insert>
3)更新
a、dao持久层的接口
public int updateStudent(Student student);
b、mapper
<update id="updateStudent" parameterType="com.lxb.domain.Student">
update Student set age=#{age} where id=#{id};
</update>
4)删除
a、dao持久层的接口
public int insertStudent(Student student);
b、mapper
<delete id="deleteStudent" parameterType="java.lang.String">
delete from Student where id=#{id};
</delete>
5)根据姓名模糊查询
a、dao持久层的接口
public List<Student> selectByName(String name);
b、mapper
<select id="selectByName" parameterType="string" resultType="com.lxb.domain.Student">
select * from student where name like #{name}
</select>
c、调用
List<Student> list= studentDao.selectByName("%李");
== '%value%' 使用的是Statement对象的字符串拼接,Preparing==
==#{name} 使用的是PreparedStatement的参数占位符(推荐)==
6)获取总记录数
a、dao持久层接口
int findCount();
b、mapper
<sleect id="countId" resultType="int">
select count(id) from student;
</select>
注:在CUD的操作中,要使用session.commit()