编程语言
首页 > 编程语言> > Mybaits 笔记1,接口编程

Mybaits 笔记1,接口编程

作者:互联网

1. 新建maven工程 ,id为quickstart,然后从properties里面的java build path,添加目录,resources目录。默认的eclipse不带resources目录。

2. pom建立坐标,

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
    
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.48</version>
</dependency>

3. 编写实体bean类,如Employee

4.编写接口,如EmployeeMapper,这里的接口的名字需要和mapper的namespace的全类名相同,另外接口的方法,要和mapper的id相同。

5.编写mybaits-config.xml,

<?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 id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="EmployeeMapper.xml"/>
  </mappers>
</configuration>

6.编写EmployeeMapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.taotao.dao.EmployeeMapper">   //此处的命名空间必须和接口的类名相同,下面的id必须和接口的方法名相同
  <select id="getEmployeeById" resultType="cn.taotao.bean.Employee">
    select * from tbl_employee where id = #{id}
  </select>
</mapper>

7.写测试类,注意一定要和bean和接口的名字有区分,比如EmployeeTest,如果相同,会导致导入包的错误。

@Test
    public void test()  {
        String resource = "mybatis-config.xml";
        SqlSession ss = null;
        try {
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(inputStream);
        ss = ssf.openSession();
        EmployeeMapper mapper = ss.getMapper(EmployeeMapper.class);
        Employee employee  = mapper.getEmployeeById(1);
        System.out.println(employee.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
        ss.close();    
        }
    }

 

标签:mapper,ss,编程,接口,Mybaits,employee,EmployeeMapper,id
来源: https://www.cnblogs.com/sdgtxuyong/p/11596503.html