MyBatis笔记(一) (2)

mapper推荐放的位置是和接口在同一个包下

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property value="com.mysql.jdbc.Driver"/> <property value="jdbc:mysql://localhost:3306/mybatis"/> <property value="root"/> <property value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/UserMapper.xml"></mapper> </mappers> </configuration> 2.4 编写MyBatis工具类 public class MyBatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } // 获取SqlSession连接 public static SqlSession getSession() { return sqlSessionFactory.openSession(); } } 2.5 创建实体类 public class User {    private int id;  //id    private String name;   //姓名    private String pwd;   //密码        //有参、无参构造函数    //set、get方法    //toString() } 2.6 编写UserMapper接口 public interface UserMapper { List<User> selectUser(); } 2.7 编写UserMapper的xml配置文件

namespace很重要,写的是对应的接口全类名

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="top.linzeliang.mapper.UserMapper"> <select resultType="top.linzeliang.pojo.User"> select * from user; </select> </mapper> 2.8 编写测试类 public class MyTest { @Test public void test() { SqlSession session = MyBatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); List<User> users = mapper.selectUser(); System.out.println(users); } }

ok,可以看到测试成功

2.9 小问题

如果你的xml文件是放在java目录下的,很可能编译运行出来会找不到这个xml文件的,因为默认它会过滤掉静态资源

如何解决?

我们可以在pom中进行声明

<resources>    <resource>        <directory>src/main/java</directory>        <includes>            <include>**/*.properties</include>            <include>**/*.xml</include>        </includes>        <filtering>false</filtering>    </resource>    <resource>        <directory>src/main/resources</directory>        <includes>            <include>**/*.properties</include>            <include>**/*.xml</include>        </includes>        <filtering>false</filtering>    </resource> </resources>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpzwxs.html