public interface IUserDao {
//查询所有用户
List<User> findAll() throws Exception;
//根据条件进行用户查询
User findByCondition(User user) throws Exception;
}
UserMapper.xml 注意里面的 namespace 和 select标签id
<mapper namespace="com.wujun.dao.IUserDao">
<select id="findAll" resultType="com.wujun.pojo.User">
select * from user
</select>
<select id="findByCondition" resultType="com.wujun.pojo.User" parameterType="com.wujun.pojo.User">
select * from user where id = #{id} and username = #{username}
</select>
</mapper>
SqlSession接口中加一个接口<T> T getMapper(Class<?> clazz);
public class IPersistenceTest {
@Test
public void test() throws Exception {
InputStream resourceAsSteam = Resources.getResourceAsSteam("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuild().build(resourceAsSteam);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setId(1L);
user.setUsername("吴俊1");
// User sqlResult = sqlSession.selectOne("com.wujun.dao.IUserDao.findByCondition", user);
// System.out.println(JSON.toJSONString(sqlResult));
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
User user1 = userDao.findByCondition(user);
System.out.println("findByCondition result:" + JSON.toJSONString(user1));
List<User> all = userDao.findAll();
for (User user2 : all) {
System.out.println("findAll result:" + JSON.toJSONString(user2));
}
}
}
返回结果
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.dom4j.io.SAXContentHandler (file:/D:/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar) to method com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser$LocatorProxy.getEncoding()
WARNING: Please consider reporting this to the maintainers of org.dom4j.io.SAXContentHandler
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
log4j:WARN No appenders could be found for logger (com.mchange.v2.log.MLog).
log4j:WARN Please initialize the log4j system properly.
findByCondition result:{"id":1,"username":"吴俊1"}
findAll result:{"id":1,"username":"吴俊1"}
findAll result:{"id":2,"username":"吴俊2"}
findAll result:{"id":3,"username":"吴俊3"}
Process finished with exit code 0