myBatis 支持自己写dao的实现类,或者用动态代理(常用)
动态代理的过程:
dao接口
public interface UserDao {
List
<User> findAll();
void saveUser(User user
);
}
测试类:
public class MybatisTest {
private InputStream in
;
private SqlSessionFactory factory
;
private SqlSession sqlSession
;
private UserDao userDao
;
@Before
public void init() throws Exception
{
in
= Resources
.getResourceAsStream("SqlMapConfig.xml");
factory
= new SqlSessionFactoryBuilder().build(in
);
sqlSession
= factory
.openSession();
userDao
= sqlSession
.getMapper(UserDao
.class);
}
@After
public void destory() throws Exception
{
sqlSession
.commit();
sqlSession
.close();
in
.close();
}
@Test
public void testFindAll() {
List
<User> users
= userDao
.findAll();
for (User user
: users
) {
System
.out
.println(user
);
}
@Test
public void testSave() throws Exception
{
User user
= new User();
user
.setUsername("一一一一一");
user
.setAddress("广东深圳");
user
.setSex("男");
user
.setBirthday(new Date());
System
.out
.println("保存之前的user"+user
);
userDao
.saveUser(user
);
System
.out
.println("保存之后的user"+user
);
}
动态代理的过程
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tNvj27kg-1599125745150)(D:\Java\1-10\00 讲义+笔记+资料\4.主流框架\31.Mybatis\mybatis\mybatis_day02\截图\非常重要的一张图-分析代理dao的执行过程.png)]
自己写dao的实现类过程:
Dao接口的实现类代码:
public class UserDaoImpl implements UserDao{
private SqlSessionFactory factory
;
public UserDaoImpl(SqlSessionFactory factory
) {
this.factory
= factory
;
}
public List
<User> findAll() {
SqlSession session
= factory
.openSession();
List
<User> users
= session
.selectList("x.xss.dao.UserDao.findAll");
session
.close();
return users
;
}
public void saveUser(User user
) {
SqlSession session
= factory
.openSession();
session
.insert("x.xss.dao.UserDao.saveUser",user
);
session
.commit();
}
测试类代码:
public class MybatisTest {
private InputStream in
;
private SqlSessionFactory factory
;
private UserDao userDao
;
@Before
public void init() throws Exception
{
in
= Resources
.getResourceAsStream("SqlMapConfig.xml");
factory
= new SqlSessionFactoryBuilder().build(in
);
userDao
= new UserDaoImpl(factory
) ;
}
@After
public void destory() throws Exception
{
in
.close();
}
@Test
public void testFindAll() {
List
<User> users
= userDao
.findAll();
for (User user
: users
) {
System
.out
.println(user
);
}
}
@Test
public void testSave() throws Exception
{
User user
= new User();
user
.setUsername("牛牛牛牛");
user
.setAddress("广东深圳");
user
.setSex("男");
user
.setBirthday(new Date());
userDao
.saveUser(user
);
}
它的执行过程:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-22kimkJZ-1599125745155)(C:\Users\2019\Desktop\1111.png)]
圳"); user.setSex(“男”); user.setBirthday(new Date()); userDao.saveUser(user); } 执行过程
以查询为例,不管是创建代理Dao实现类对象 ,还是编写Dao实现类,最终都是去实行selectList方法,后面的过程就是一样了!