MyBatis(三)--注解开发

1 注解开发介绍

1.1 为什么要有注解开发

注解可以简化开发操作,省略映射配置文件的编写

1.2 常用的注解

@Insert(“查询的SQL语句”):实现新增操作

@Update(“修改的SQL语句”):实现修改操作

@Delete(“删除的SQL语句”):实现删除操作

@Select(“查询的SQL语句”):实现查询操作

1.3配置映射关系(在核心配置文件中MyBatisConfig.xml)

<!--  引入映射配置关系 -->  
   <mappers>
       <package name="com.liyiyi.Mapper"/>   一定要是接口所在的包名
   </mappers>
</configuration>

说白了这个映射关系就是在原先配置核心映射文件那块用它替换下来。

2 注解开发实现--增 删 改 查

Student类
public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Student(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Student() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

StudentMapper接口
public interface StudentMapper {
    //查询全部
    @Select("SELECT * FROM student")
    public abstract List<Student> selectAll();

    //新增操作
    @Insert("INSERT INTO student VALUES(#{id},#{name},#{age})")
    public abstract Integer insert(Student student);

    //修改操作
    @Update("UPDATE student SET name =#{name},age=#{age} WHERE id =#{id}")
    public abstract Integer update(Student student);

    //删除操作
    @Delete("DELETE FROM student WHERE id =#{id}")
    public abstract Integer delete(Integer id);
}

Test类

public class Test01 {
 //查询全部的方法
    @Test
    public void selectAll () throws IOException {
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBaitsConfig.xml");
        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.获取StudentMapper接口的实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.调用实现类对象
        List<Student> list = mapper.selectAll();
        for (Student student : list) {
            System.out.println(student);
        }
        //6.释放资源
        is.close();
        sqlSession.close();
    }

//新增的方法
    @Test
    public void Insert() throws Exception{
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBaitsConfig.xml");
        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.获取StudentMapper接口的实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.调用实现类对象
        Student student =new Student(9,"于九",23);
        Integer insert = mapper.insert(student);
        System.out.println(insert);
        //6.释放资源
        is.close();
        sqlSession.close();

    }

//修改的方法
@Test
public void Update() throws Exception{
    //1.加载核心配置文件
    InputStream is = Resources.getResourceAsStream("MyBaitsConfig.xml");
    //2.获取SqlSession工厂对象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    //3.通过工厂对象获取SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    //4.获取StudentMapper接口的实现类对象
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    //5.调用实现类对象
    Student student =new Student(9,"于九九",23);
    Integer update = mapper.update(student);
    System.out.println(update);
    //6.释放资源
    is.close();
    sqlSession.close();

}
//删除操作
@Test
public void Delete() throws Exception{
    //1.加载核心配置文件
    InputStream is = Resources.getResourceAsStream("MyBaitsConfig.xml");
    //2.获取SqlSession工厂对象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    //3.通过工厂对象获取SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    //4.获取StudentMapper接口的实现类对象
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    //5.调用实现类对象
    Integer delete = mapper.delete(9);
    System.out.println(delete);
    //6.释放资源
    is.close();
    sqlSession.close();

}

}

3 注解实现多表操作

说明:数据库和用mapper进行多表查询时一样的数据库,一直用的db27。

 3.1 一对一(案例参考用映射文件mapper那个)

Card类
public class Card {
    private Integer id;    //主键id
    private String number;  //身份证号

    private Person p;  //所属人的对象

    public Card(Integer id, String number) {
        this.id = id;
        this.number = number;
    }

    public Card() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    @Override
    public String toString() {
        return "Card{" +
                "id=" + id +
                ", number='" + number + '\'' +
                ", p=" + p +
                '}';
    }
}

Person 类
public class Person {
    private Integer id;  //主键id
    private String name; //人的姓名
    private Integer age; //人的年龄

    public Person(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Person() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

两个接口

public interface CardMapper {
    //查询全部
    @Select("SELECT * FROM card")
    @Results({
            @Result(column = "id" ,property = "id"),
            @Result(column = "number",property = "number"),
            @Result(
                    property = "p",    //被包含对象的变量名
                    javaType = Person.class,  //被包含对象的实际数据类型
                    column = "pid",      //根据查询出的card表中的pid字段来查询person表
                    /*
                    * one=@one() 一对一固定写法
                    * select属性:指定调用哪个接口中的哪个方法
                    * */
                    one =@One(select = "com.liyiyi.OneToOne.PersonMapper.selectById")
                    //一定要写全类名
            )

    })
    public abstract List<Card> selectAll();

}


public interface PersonMapper {
    //根据id查询
    @Select("SELECT * FROM person WHERE id =#{id}")
    public abstract Person selectById(Integer id);
}

测试类

public class Test01 {
    @Test
    public void selectAll() throws Exception {
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.获取CardMapper接口的实现类对象
        CardMapper mapper = sqlSession.getMapper(CardMapper.class);
        //5.调用实现类对象中的方法,接收结果
        List<Card> cards = mapper.selectAll();
        for (Card card : cards) {
            System.out.println(card);
        }

        sqlSession.close();
        is.close();
    }
}

3.2 一对多

 (1)Javabean

Student 类
public class Student {
    private Integer id;  //主键id
    private String  name;   //学生姓名
    private Integer age;    //学生年龄


    public Student() {
    }

    public Student(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;

    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }



    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

CLasses类


public class Classes {
    private Integer id;  //主键id
    private String name;  //班级名字

    private List<Student> students;  //班级中所有的学生对象

    public Classes(Integer id, String name, List<Student> students) {
        this.id = id;
        this.name = name;
        this.students = students;
    }

    public Classes() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    @Override
    public String toString() {
        return "Classes{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", students=" + students +
                '}';
    }
}

(2)Mapper接口

ClassesMapper接口
public interface ClassesMapper {
    //查询全部
    @Select("SELECT * FROM classes")
    @Results({
            @Result(column = "id",property ="id" ),  //表中id这个属性是要给classes这个实体类中的id赋值
            @Result(column = "name",property ="name" ),
            @Result(
                    property = "students",  //被包含对象的名字
                    javaType = List.class,  //被包含对象的类型
            column = "id",       //根据我们查询出的classes表中的id字段查询我们的Student

            /*
            * many =@Many()  1对多的固定写法
            * select属性:指定调用哪个接口中的哪个查询方法
            * */
            many =@Many(select = "com.liyiyi.OneToMany.StudentMapper.selectByCid")
            )
    })
    public abstract List<Classes> selectAll();

}

StudentMapper接口

public interface StudentMapper {
    //根据cid查询student表
    @Select("SELECT * FROM student WHERE cid =#{cid}")
    public abstract List<Student> selectByCid(Integer cid);
}

(3)测试类

public class Test01 {
    @Test
    public void selectAll() throws Exception {
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.获取CardMapper接口的实现类对象
        ClassesMapper mapper = sqlSession.getMapper(ClassesMapper.class);
        //5.调用实现类对象中的方法,接收结果
        List<Classes> classes = mapper.selectAll();
        for (Classes c : classes) {
            System.out.println(c.getId()+","+c.getName());
            List<Student> students =c.getStudents();
            for (Student student : students) {
                System.out.println(student);
            }
        }

        sqlSession.close();
        is.close();
    }
}

(4)对核心配置文件的再说明

 3.3 多对多

 (1)javaBean

Student类

public class Student {
    private Integer id;  //主键id
    private String  name;   //学生姓名
    private Integer age;    //学生年龄

    private List<Course> courses;   //学生们所选择的课程对象。
    public Student() {
    }

    public Student(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;

    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public List<Course> getCourses() {
        return courses;
    }

    public void setCourses(List<Course> courses) {
        this.courses = courses;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Course类

public class Course {
    private Integer id;  //主键id
    private String name; //课程名称

    public Course(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Course() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Course{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

(2) 接口

CourseMapper接口

public interface CourseMapper {
    //根据学生id查询所选课程
    @Select("SELECT c.id,c.name FROM stu_cr sc,course c WHERE sc.cid=c.id AND sc.sid=#{id}")
    public abstract List<Course> selectBySid(Integer id);
}


StudentMapper接口

public interface StudentMapper {
    //查询全部
    @Select("SELECT * FROM student")
    //若是不想要查询出没选课的学生用下面这条语句
   // @Select("SELECT DISTINCT s.id,s.name,s.age FROM student s,stu_cr sc WHERE sc.sid=s.id")

    @Results({
            @Result(column = "id",property = "id"),
            @Result(column = "name",property = "name"),
            @Result(column = "age",property = "age"),
            @Result(
                    property = "courses",   //被包含对象的名字。
                    javaType = List.class,  //被包含对象的实际数据类型。
                    column = "id",         //根据查出的Student表的id来作为关联条件,去查询中间表和课程表。

                    many = @Many(select = "com.liyiyi.ManyToMany.CourseMapper.selectBySid")
            )
    })
    public abstract List<Student> selectAll();

}

(3)Test类

public class Test01 {
    @Test
    public void selectAll() throws Exception {
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.获取CardMapper接口的实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.调用实现类对象中的方法,接收结果
        List<Student> list = mapper.selectAll();
        for (Student student : list) {
            System.out.println(student.getId()+","+student.getAge()+","+student.getName());
            List<Course> courses = student.getCourses();
            for (Course cours : courses) {
                System.out.println(cours);
            }
        }
        sqlSession.close();
        is.close();
    }
}

4 构建SQL语句

  • 我们之前通过注解开发时,相关 SQL 语句都是自己直接拼写的。一些关键字写起来比较麻烦、而且容易出错。
  • MyBatis 给我们提供了 org.apache.ibatis.jdbc.SQL 功能类,专门用于构建 SQL 语句

 (2)增删改查的实现

 

 (1)Student表

public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Student(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Student() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

(2)StudentMapper接口

public interface StudentMapper {
    //查询全部
  @SelectProvider(type = ReturnSql.class,method = "getSelectAll")
    public abstract List<Student> selectAll();

    //新增操作
   @InsertProvider(type =ReturnSql.class,method = "getInsert")
    public abstract Integer insert(Student student);

    //修改操作
  @UpdateProvider(type =ReturnSql.class,method = "Update")
    public abstract Integer update(Student student);

    //删除操作
   @DeleteProvider(type =ReturnSql.class,method = "Delect")
    public abstract Integer delete(Integer id);
}

(3)sql类

public class ReturnSql {

//查询
    public String getSelectAll(){
        //以匿名内部类的形式
        return  new SQL(){

            {
                SELECT("*");
                FROM("student");
            }

        }.toString();

    }

//新增
    public String getInsert(Student stu){
        return new SQL(){
            {
                INSERT_INTO("student");
                INTO_VALUES("#{id},#{name},#{age}");
            }
        }.toString();
    }
//修改
public String Update(Student stu){
    return new SQL(){
        {
            UPDATE("student");
            SET("name=#{name}","age=#{age}");
            WHERE("id =#{id}");

        }
    }.toString();
}
//删除
public String Delect(Integer id){
    return new SQL(){
        {
            DELETE_FROM("student");
            WHERE("id =#{id}");

        }
    }.toString();
}
}

(4)Test类

public class Test01 {
    //查询全部的方法
    @Test
    public void selectAll () throws IOException {
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBaitsConfig.xml");
        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.获取StudentMapper接口的实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.调用实现类对象
        List<Student> list = mapper.selectAll();
        for (Student student : list) {
            System.out.println(student);
        }
        //6.释放资源
        is.close();
        sqlSession.close();
    }

    //新增的方法
    @Test
    public void Insert() throws Exception{
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBaitsConfig.xml");
        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.获取StudentMapper接口的实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.调用实现类对象
        Student student =new Student(9,"于九",23);
        Integer insert = mapper.insert(student);
        System.out.println(insert);
        //6.释放资源
        is.close();
        sqlSession.close();

    }

    //修改的方法
    @Test
    public void Update() throws Exception{
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBaitsConfig.xml");
        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.获取StudentMapper接口的实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.调用实现类对象
        Student student =new Student(9,"于九九",23);
        Integer update = mapper.update(student);
        System.out.println(update);
        //6.释放资源
        is.close();
        sqlSession.close();

    }
    //删除操作
    @Test
    public void Delete() throws Exception{
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBaitsConfig.xml");
        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.获取StudentMapper接口的实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.调用实现类对象
        Integer delete = mapper.delete(9);
        System.out.println(delete);
        //6.释放资源
        is.close();
        sqlSession.close();
    }
}

猜你喜欢

转载自blog.csdn.net/m0_62567916/article/details/125440994
今日推荐