结构
编写数据源 spring-dao.xml
sqlSessionFactory
sqlSessionTemplate
需要给接口加实现类
将自己写的实现类,注入到Spring中
package com.wang.mapper;
import com.wang.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper{
//我们的所有操作.都使用sqlSession来执行,现在使用SqlSessionTemplate;
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
测试使用即可
import com.wang.mapper.UserMapper;
import com.wang.pojo.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.util.List;
public class MyTest {
@Test
public void MyTest() throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
List users = userMapper.selectUser();
System.out.println(users);
}
}
applicationContext.xml