`

MyBatis3注解的关系映射

阅读更多
1. MyBatis3注解的关系映射
   
1) 一对一映射;
2) 一对多映射;


package com.andrew.mappers;
import org.apache.ibatis.annotations.Select;
import com.andrew.model.Address;
public interface AddressMapper {
    @Select("select * from t_address where id=#{id}")
    public Address findById(Integer id);
}


package com.andrew.mappers;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import com.andrew.model.Grade;
public interface GradeMapper {
    @Select("select * from t_grade where id=#{id}")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="gradeName",property="gradeName"),
    @Result(column="id",property="students",many=@Many(select="com.andrew.mappers.StudentMapper.selectStudentByGradeId"))
    })
    public Grade findById(Integer id);
}


package com.andrew.mappers;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.andrew.model.Student;
public interface StudentMapper {
    @Insert("insert into t_student values(null,#{name},#{age},1,1,1,1)")
    public int insertStudent(Student student);
    @Update("update t_student set name=#{name},age=#{age} where id=#{id}")
    public int updateStudent(Student student);
    @Delete("delete from t_student where id=#{id}")
    public int deleteStudent(int id);
    @Select("select * from t_student where id=#{id}")
    public Student getStudentById(Integer id);
    @Select("select * from t_student")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="name",property="name"),
        @Result(column="age",property="age")
    })
    public List<Student> findStudents();
    @Select("select * from t_student where id=#{id}")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="name",property="name"),
        @Result(column="age",property="age"),
    @Result(column="addressId",property="address",one=@One(select="com.andrew.mappers.AddressMapper.findById"))
    })
    public Student selectStudentWithAddress(int id);
    @Select("select * from t_student where gradeId=#{gradeId}")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="name",property="name"),
        @Result(column="age",property="age"),
    @Result(column="addressId",property="address",one=@One(select="com.andrew.mappers.AddressMapper.findById"))
    })
    public Student selectStudentByGradeId(int gradeId);
    @Select("select * from t_student where id=#{id}")
    @Results({
        @Result(id=true,column="id",property="id"),
        @Result(column="name",property="name"),
        @Result(column="age",property="age"),
    @Result(column="addressId",property="address",one=@One(select="com.andrew.mappers.AddressMapper.findById")),
        @Result(column="gradeId",property="grade",one=@One(select="com.andrew.mappers.GradeMapper.findById"))
    })
    public Student selectStudentWithAddressAndGrade(int id);
}


package com.andrew.model;
public class Address {
    private Integer id;
    private String sheng;
    private String shi;
    private String qu;
    @Override
    public String toString() {
        return "Address [id=" + id + ", sheng=" + sheng + ", shi=" + shi
                + ", qu=" + qu + "]";
    }
    // getter and setter
}


package com.andrew.model;
import java.util.List;
public class Grade {
    private Integer id;
    private String gradeName;
    private List<Student> students;
    @Override
    public String toString() {
        return "Grade [id=" + id + ", gradeName=" + gradeName + "]";
    }
    // getter and setter
}


package com.andrew.model;
public class Student {
    private Integer id;
    private String name;
    private Integer age;
    private Address address;
    private Grade grade;
    public Student() {
        super();
    }
    public Student(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }
    public Student(Integer id, String name, Integer age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age
                + ", address=" + address + ", grade=" + grade + "]";
    }
    // getter and setter
}


package com.andrew.service;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.andrew.mappers.GradeMapper;
import com.andrew.mappers.StudentMapper;
import com.andrew.model.Grade;
import com.andrew.model.Student;
import com.andrew.util.SqlSessionFactoryUtil;
public class StudentGradeTest {
    private SqlSession sqlSession = null;
    private StudentMapper studentMapper = null;
    private GradeMapper gradeMapper = null;
    @Before
    public void setUp() throws Exception {
        sqlSession = SqlSessionFactoryUtil.openSession();
        studentMapper = sqlSession.getMapper(StudentMapper.class);
        gradeMapper = sqlSession.getMapper(GradeMapper.class);
    }
    @After
    public void tearDown() throws Exception {
        sqlSession.close();
    }
    @Test
    public void testSelectStudentWithAddress() {
        Student student = studentMapper.selectStudentWithAddress(2);
        System.out.println(student);
    }
    @Test
    public void testSelectGradeWithStudents() {
        Grade grade = gradeMapper.findById(2);
        System.out.println(grade);
        List<Student> studentList = grade.getStudents();
        for (Student student : studentList) {
            System.out.println(student);
        }
    }
    @Test
    public void testSelectStudentWithAddressAndGrade() {
        Student student = studentMapper.selectStudentWithAddressAndGrade(1);
        System.out.println(student);
    }
}
分享到:
评论

相关推荐

    MyBatis注解配置映射器:动态SQL的实现

    总结来说,MyBatis注解配置提供了一种简洁的SQL映射方式,而动态SQL功能则极大地增强了查询的灵活性。在开发过程中,熟练掌握这两点,可以提升开发效率,同时使代码更加易于理解和维护。通过实践项目"MyBatisPro12...

    MyBatis 采用注解方式实现CRUD

    MyBatis 是一款深受开发者喜爱的持久层框架,它提供了灵活的SQL映射和对象关系映射功能,使得Java开发者可以方便地进行数据库操作。在传统的MyBatis配置中,我们通常通过XML文件来定义SQL语句和映射规则。然而,随着...

    MyBatis基于注解简单案例

    通过这个简单的MyBatis注解案例,我们可以了解到如何利用MyBatis进行基本的数据库操作,包括选择性地使用注解替代XML配置,以及如何在Spring框架下集成MyBatis。在实际项目中,还可以结合MyBatis的其他特性,如结果...

    MyBatis注解配置映射器:一对多关系的实现

    本文将深入探讨如何使用MyBatis的注解配置来实现一对多关系映射,以此来提高开发效率并减少代码冗余。 首先,我们需要理解一对多关系的概念。在数据库设计中,一对多关系表示一个表中的记录可以对应另一个表中的多...

    MyBatis注解配置映射器:一对一关系的实现

    在一对一关系的实现中,MyBatis注解可以帮助我们轻松处理两个实体类之间的一对一关联,无需编写复杂的XML映射文件。 首先,我们需要了解MyBatis中的@Select、@Insert、@Update和@Delete这四个基本注解,它们分别...

    Spring mvc 和 mybatis 整合,mybatis使用注解模式

    总结来说,Spring MVC与MyBatis的整合使得我们能够充分利用两者的优势:Spring MVC提供了强大的MVC架构和依赖注入,而MyBatis的注解模式则简化了SQL映射。通过这种方式,开发者可以更专注于业务逻辑,提高开发效率和...

    springboot+mybatis通用注解

    SpringBoot简化了Spring应用的初始搭建以及配置过程,而MyBatis则是一个优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。当我们把两者结合起来,可以构建出高效、便捷的后端服务。 在"springboot+...

    MyBatis一对多映射

    综上所述,MyBatis的一对多映射是通过XML映射文件或注解实现的,它能有效地处理主表和从表之间的关联关系,简化了数据操作。在实际开发中,根据项目需求和性能考虑,合理选择映射方式和加载策略,可以大大提高开发...

    spring+springMvc+MyBatis+注解

    MyBatis是一个优秀的持久层框架,它简化了SQL操作,允许开发者直接编写SQL语句,避免了过多的ORM(对象关系映射)操作。MyBatis通过XML配置或注解方式,将SQL与Java代码绑定,提供动态SQL支持,使得数据库操作更加...

    mybatis使用注解方式简单实现的Demo

    MyBatis 是一款著名的持久层框架,它支持定制化 SQL、存储过程以及高级映射。在本示例中,我们将探讨如何使用 MyBatis 的注解方式来简化数据库操作。这个"mybatis使用注解方式简单实现的Demo"旨在帮助初学者理解 ...

    MyBatis关于注解的配置

    `ExamSystemByNote`可能是一个示例项目,其中展示了如何在考试系统中使用MyBatis注解进行数据操作。通过阅读该项目的代码,你可以了解到注解在实际项目中的具体使用。 总的来说,MyBatis的注解配置为开发者提供了...

    Spring3Struts2Mybatis3注解开发实例

    "Spring3Struts2Mybatis3注解开发实例"是一个集成这三大框架的项目,它利用注解来简化配置,提高开发效率。这个项目集成了Spring的依赖注入、Struts2的MVC架构和Mybatis的持久层操作,旨在为开发者提供一个高效且...

    spring mvc mybatis 注解版

    MyBatis注解简化了传统的XML配置,可以在Mapper接口和实现类中直接定义SQL语句。主要的注解有: 1. `@Select`:用于查询操作,可以包含一个SQL查询语句。 2. `@Insert`:插入数据,可以包含一个INSERT语句,支持...

    Spring 整合mybatis(注解&xml版声明式事务).pdf

    映射器配置通常包括MyBatis的XML配置文件或注解配置,它负责指定SQL语句和Mapper接口之间的映射关系。 6. 开启注解式事务管理或声明式事务管理。在Spring配置文件中开启注解事务,通常通过标注@Transactional注解...

    Mybatis接口注解

    3. **类型安全**:因为注解中的 SQL 参数是方法参数的一部分,类型检查在编译时就能完成,降低了运行时错误的可能性。 在 `mybatis-start2` 这个压缩包中,可能包含了使用 Mybatis 接口注解的示例项目。这个项目...

    spring 3.05 + spring 3.05 mvc + mybatis (注解驱动) maven整合应用示例

    - 使用MyBatis注解在DAO接口和实现类中定义SQL语句,例如`@Select`、`@Insert`、`@Update`和`@Delete`。 - 在Spring MVC的控制器类中,通过@Autowired注解注入服务层bean,调用业务逻辑方法。 6. **源码分析**: ...

    Mybatis关联映射Demo

    3. **多对多(ManyToMany)映射**:这种关系更为复杂,通常涉及中间表来存储两个实体的关联信息。Mybatis通过`&lt;association&gt;`和`&lt;collection&gt;`的组合来实现,需要在映射文件中定义两个实体间的关联关系。 在...

    springmvc3+spring+mybatis3整合项目 注解实现

    这个整合项目是基于Spring 3.0.5、Spring MVC 3和MyBatis 3.0.2版本,采用注解方式进行配置,简化了XML配置文件,提高了开发效率。 Spring MVC是Spring框架的一部分,主要负责Web请求的处理。在本项目中,通过注解...

    SSM框架的学习与应用-Java EE企业级应用开发学习记录(第五天)MyBatis的注解开发

    3.进行了一对一关联映射和一对多关联映射的测试,测试类齐全,且具备注解方式和xml方式查询 4.包含项目所需的全部配置文件resources 5.包含项目数据库的sql文件,只需要创建数据库导入数据即可 配合上文章,可以做到...

    mybatis中注解映射SQL示例代码

    MyBatis中注解映射SQL示例代码 MyBatis是一款流行的持久层框架,它提供了多种方式来映射SQL语句,其中之一便是使用注解的方式。下面我们将通过示例代码来介绍MyBatis中注解映射SQL的相关知识点。 结果集分页 在...

Global site tag (gtag.js) - Google Analytics