MyBatis 入门实例注解配置

3、MyBatis 入门实例注解配置

   ①、上面的前面四步都是一样的,但是第五步不一样,我们不需要创建 personMapper.xml 文件,首先在 src 目录下创建 personMapper.java 文件

  

   内容如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

package com.ys.annocation;

import org.apache.ibatis.annotations.Delete;

import org.apache.ibatis.annotations.Insert;

import org.apache.ibatis.annotations.Select;

import org.apache.ibatis.annotations.Update;

import com.ys.bean.Person;

public interface PersonMapper {

     

    @Insert("insert into person(pid,pname,page) values(#{pid},#{pname},#{page})")

    public int add(Person person);

     

    @Select("select * from person where pid = #{pid}")

    public Person getPerson(int pid);

     

    @Update("update person set pname=#{pname},page=#{page} where pid = #{pid}")

    public int updatePerson(Person preson);

     

    @Delete("delete from person where pid=#{pid}")

    public int deletePerson(int pid);

}

  ②、向 mybatis-configuration.xml 配置文件中注册 personMapper.xml 文件

   ③、编写测试类

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

@Test

public void testAnnocation(){

    PersonMapper mapper = session.getMapper(PersonMapper.class);

    Person p = new Person();

    p.setPid(7);

    p.setPname("abc");

    p.setPage(11);

    //调用增加方法

    mapper.add(p);

    //调用查询方法

    Person p1 = mapper.getPerson(3);

    System.out.println(p1);

    //调用更新方法

    p.setPage(100);

    mapper.updatePerson(p);

    //调用删除方法

    mapper.deletePerson(7);

    session.commit();

    session.close();

}

猜你喜欢

转载自blog.csdn.net/weixin_41577923/article/details/84236945