赞
踩
MyBatis核心的API: SqlSession
SqlSessionFactoryBuilder: .build()
SqlSessionFactory:
openSession
SqlSession:
insert/ update/ delete/ select
一、可以采用接口加sql语句的方式来解决,sql语句理解为是接口的实现:
Java代码
- package com.john.hbatis.mapper;
-
- import com.john.hbatis.model.User;
-
- public interface IUserMapper {
- User getUserById(int id);
- }
<mapper namespace="com.john.hbatis.mapper.IUserMapper"> <select id="getUserById"
- @Test
- public void queryInInterfaceWayTest() {
- SqlSession session = sqlSessionFactory.openSession();
- IUserMapper mapper = session.getMapper(IUserMapper.class); // 如果namespace和接口全限定名不一致,报org.apache.ibatis.binding.BindingException: Type interface com..IUserMapper is not known to the MapperRegistry异常。
- User user = mapper.getUserById(1);
- log.info("{}: {}", user.getName(), user.getAddress());
- }
- package com.john.hbatis.mapper;
-
- import org.apache.ibatis.annotations.Select;
-
- import com.john.hbatis.model.User;
-
- public interface IUserMapper2 {
- @Select({ "select * from `user` where id = #{id}" })
- User getUserById(int id);
- }
<mappers> <mapper class="com.john.hbatis.mapper.IUserMapper2" /> </mappers>
sqlSessionFactory.getConfiguration().addMapper(IUserMapper2.class);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。