package com.kang.mapper;import java.util.List;import com.kang.pojo.User;public interface UserMapper { //根据用户id查询用户信息 public User findUserById(int id) throws Exception; //查询用户列表 public List2、配置xml文件 UserMapper.xmlfindUserByUsername(String username) throws Exception; //添加用户信息 public void insertUser(User user)throws Exception; }
注意到配置文件中的id属性值和map接口中的方法名是一一对应的。 3、在SqlMapConfig.xml中加入映射文件select LAST_INSERT_ID() insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
4、测试代码
package com.kang.test;import java.io.IOException;import java.io.InputStream;import java.util.Date;import java.util.List;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Before;import org.junit.Test;import com.kang.mapper.UserMapper;import com.kang.pojo.User;public class UserTest { // 会话工厂 private SqlSessionFactory sqlSessionFactory; @Before public void createSqlSessionFactory() throws IOException { // 配置文件SqlMapConfig.xml在类路径下 String resource = "SqlMapConfig.xml"; // 得到配置文件流 InputStream inputStream = Resources.getResourceAsStream(resource); // 创建会话工厂,传入mybatis的配置文件信息 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testFindUserById() throws Exception { //获取session SqlSession session = sqlSessionFactory.openSession(); //获取mapper接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); //调用代理对象方法 User user = userMapper.findUserById(27); System.out.println(user); //关闭session session.close(); System.out.println("---------执行完毕-----------"); } @Test public void testFindByUsername() throws Exception{ //获取session SqlSession session = sqlSessionFactory.openSession(); //获取mapper接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); //调用代理对象方法 Listlist=userMapper.findUserByUsername("张"); for (User user : list) { System.out.println(user); } //关闭session session.close(); System.out.println("---------执行完毕-----------"); } @Test public void testInsert() throws Exception{ User user=new User(); user.setUsername("cxk"); user.setSex("1"); user.setBirthday(new Date()); user.setAddress("四川成都"); SqlSession session=sqlSessionFactory.openSession(); UserMapper userMapper=session.getMapper(UserMapper.class); userMapper.insertUser(user); session.commit(); //关闭session session.close(); System.out.println("---------执行完毕-----------"); } }
5、单元测试
id查询测试
模糊查询测试
插入数据测试