发表于: 2016-09-11 20:44:54

1 2389


今天完成的任务

  今天继续学习mybatis的开发方法主要学习原始Dao开发方式和mapper动态代理方式

原始Dao开发方式,原始Dao开发方法需要程序员编写Dao接口和Dao实现类。

Public interface UserDao {

public User getUserById(int id) throws Exception;

public void insertUser(User user) throws Exception;

}


Public class UserDaoImpl implements UserDao {

//注入SqlSessionFactory

public UserDaoImpl(SqlSessionFactory sqlSessionFactory){

this.setSqlSessionFactory(sqlSessionFactory);

}

private SqlSessionFactory sqlSessionFactory;

@Override

public User getUserById(int id) throws Exception {

SqlSession session = sqlSessionFactory.openSession();

User user = null;

try {

//通过sqlsession调用selectOne方法获取一条结果集

//参数1:指定定义的statement的id,参数2:指定向statement中传递的参数

user = session.selectOne("test.findUserById", 1);

System.out.println(user);

} finally{

session.close();

}

return user;

}

@Override

Public void insertUser(User user) throws Exception {

SqlSession sqlSession = sqlSessionFactory.openSession();

try {

sqlSession.insert("insertUser", user);

sqlSession.commit();

} finally{

session.close();

}

}

}

原始Dao开发方式存在以下问题

Dao方法体存在重复代码:通过SqlSessionFactory创建SqlSession,调用SqlSession的数据库操作方法

调用sqlSession的数据库操作方法需要指定statementid,这里存在硬编码,不得于开发维护


mapper动态代理方式

Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。

Mapper接口开发需要遵循以下规范:

1、 Mapper.xml文件中的namespacemapper接口的类路径相同。

2、  Mapper接口方法名和Mapper.xml中定义的每个statementid相同

3、 Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql parameterType的类型相同

4、 Mapper接口方法的输出参数类型和mapper.xml中定义的每个sqlresultType的类型相同


<?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="cn.itcast.mybatis.mapper.UserMapper">

<!-- 根据id获取用户信息 -->

<select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">

select * from user where id = #{id}

</select>

<!-- 自定义条件查询用户列表 -->

<select id="findUserByUsername" parameterType="java.lang.String" 

resultType="cn.itcast.mybatis.po.User">

  select * from user where username like '%${value}%' 

</select>

<!-- 添加用户 -->

<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">

<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">

select LAST_INSERT_ID() 

</selectKey>

 insert into user(username,birthday,sex,address) 

 values(#{username},#{birthday},#{sex},#{address})

</insert>


</mapper>


总结

selectOneselectList

动态代理对象调用sqlSession.selectOne()sqlSession.selectList()是根据mapper接口方法的返回值决定,如果返回list则调用selectList方法,如果返回单个对象则调用selectOne方法。

 namespace

mybatis官方推荐使用mapper代理方法开发mapper接口,程序员不用编写mapper接口实现类,使用mapper代理方法时,输入参数可以使用pojo包装对象或map对象,保证dao的通用性。


看视频看的头晕,进度其实还可以,不是太快。mybatis还有18级没看完。明天会继续完成。



返回列表 返回列表
评论

    分享到