Mybatis3+Spring3集成测试
程序员文章站
2022-05-11 09:00:27
...
一、简介
二、包结构展示
三、重点部分实现
********************************************************
一、简介
因为大家对mybatis不是很熟悉,这里通过一个简单的实例展示一下,mybatis和spring集成后的开发过程。
二、包结构展示
三、重点部分实现
测试类:UserServiceTest
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath*:applicationContext-test.xml" }) public class UserServiceTest { private UserService userService; @Resource(name = "userService") public void setUserService(UserService userService) { this.userService = userService; } @Test public void testSaveUser() { User user = new User(); user.setId(2); user.setAge(2); user.setUsername("张海兵"); userService.saveUser(user); } }
业务逻辑实现类:UserServiceImpl.java
@Component("userService") public class UserServiceImpl implements UserService { private UserDao userDao; @Resource(name="userDao") public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void saveUser(User user) { userDao.save(user); }
DAO实现类:
@Component("userDao") public class UserDaoImpl implements UserDao { @Resource(name="userMapper") private UserMapper userMapper; @Override public void save(User user) { userMapper.save(user); System.out.println(user.getUsername() + " save successful!"); }
配置文件:UserMapper.xml
<!-- Mapper文件最好放在与Dao接口同一目次下 --> <mapper namespace="com.pb.mybatis.mapper.UserMapper"> <!-- 定义要操纵的SQL语句 --> <insert id="save" parameterType="com.pb.mybatis.entity.User"> INSERT INTO user(id,age,gender,username,password,mail,nickname,site) VALUES(#{id},#{age},#{gender},#{username},#{password},#{mail},#{nickname},#{site}) </insert>