idea开发必须是把Mapper文件与配置文件放到Resources标记的classpath目录下,eclips好像放到哪都行指定好路径就可以了,
maven里面做好配置resources的路径,不然更新依赖 工程结构标记又没了
src/main/java/Resources
1.原生使用sqlsessionFcatory去做数据库操作,很麻烦
@Test public void qeryByNameTest() throws IOException { //加载核心配置文件 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); //创造sqlsessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); Listlist= sqlSession.selectList("user.queryByName","王五"); for (User u:list){ System.out.println(u.toString()); }
2.使用mapper动态代理由mybatis根据你的 mapper类的接口名与映射文件里面的id名一致,指明了namespace的是哪个mapper类即可
public interface UserMapper { //遵循四个原则 //接口 方法名 == User.xml 中 id 名 //返回值类型 与 Mapper.xml文件中返回值类型要一致 //方法的入参类型 与Mapper.xml中入参的类型要一致 //命名空间 绑定此接口 public User queryById(Integer id);}@Test public void userMapperTest(){ InputStream inputStream = null; { try { inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); } catch (IOException e) { e.printStackTrace(); } } //创造sqlsessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession= sqlSessionFactory.openSession(); UserMapper userMapper=sqlSession.getMapper(UserMapper.class); User user= userMapper.queryById(10); System.out.println(user);}
SqlMapConfig.xmlUserMapper.xml
SELECT LAST_INSERT_ID() INSERT INTO `user` (username,birthday,sex,address) VALUES (#{username},#{birthday},#{sex},#{address})UPDATE `user` SET username = #{username} WHERE id = #{id} delete from user where id=#{id}