小峰mybatis(4)mybatis使用注解配置sql映射器

主流开发还是使用xml来配置;使用注解配置比较快,但是不支持所有功能;有些功能还是得用配置文件;

一、基本映射语句:                                

@Inert

@Update

@Delete

@Select

二、结果集映射语句                                

项目结够:

Student.java model实体类:

package com.cy.model;

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

    public Student(){

    }

    public Student(String name, Integer age){
        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 + "]";
    }

}

mybatis-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>
    <properties resource="jdbc.properties"/>
    <!-- 别名 -->
    <typeAliases>
        <package name="com.cy.model"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
                <dataSource type="POOLED">
                    <property name="driver" value="${jdbc.driverClassName}" />
                    <property name="url" value="${jdbc.url}" />
                    <property name="username" value="${jdbc.username}" />
                    <property name="password" value="${jdbc.password}" />
                </dataSource>
        </environment>
        <environment id="test">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClassName}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="com.cy.mapper"/>
    </mappers>
</configuration>

StudentMapper.java 接口:

package com.cy.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Select;

import com.cy.model.Student;

public interface StudentMapper {

    //插入
    @Insert("insert into t_student values(null, #{name}, #{age})")
    public int inertStudent(Student student);

    //更新
    @Update("update t_student set name=#{name}, age=#{age} where id = #{id}")
    public int updateStudent(Student stu);

    //删除
    @Delete("delete from t_student where id=#{id}")
    public int deleteStudent(int id);

    //根据id查找学生
    @Select("select * from t_student where id=#{id}")
    public Student getStudentById(Integer id);

    //查询所有学生  结果集映射  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();

}

测试代码StudentTest.java:

package com.cy.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.cy.mapper.StudentMapper;
import com.cy.model.Student;
import com.cy.util.SqlSessionFactoryUtil;

public class StudentTest {
    private static Logger logger = Logger.getLogger(StudentTest.class);

    private SqlSession sqlSession=null;
    private StudentMapper studentMapper=null;

    @Before
    public void setUp() throws Exception {
        sqlSession=SqlSessionFactoryUtil.openSession();
        studentMapper=sqlSession.getMapper(StudentMapper.class);
    }

    @After
    public void tearDown() throws Exception {
        sqlSession.close();
    }

    @Test
    public void testInsertStudent() {
        logger.info("测试insertStudent");
        Student stu = new Student("cpp", 12);
        int count = studentMapper.inertStudent(stu);
        sqlSession.commit();
    }

    @Test
    public void testUpdateStudent() {
        logger.info("测试updateStudent");
        Student stu = new Student("cppp", 13);
        stu.setId(14);
        int count = studentMapper.updateStudent(stu);
        sqlSession.commit();
    }

    @Test
    public void testDeleteStudent() {
        logger.info("测试删除学生");
        int count = studentMapper.deleteStudent(14);
        sqlSession.commit();
    }

    @Test
    public void testGetById(){
        logger.info("根据id查找学生");
        Student stu = studentMapper.getStudentById(1);
        System.out.println(stu);
    }

    @Test
    public void testFindStudent() {
        logger.info("测试查询所有学生");
        List<Student> students = studentMapper.findStudents();
        for(Student student : students){
            System.out.println(student);
        }
    }
}

三、使用注解 一对一映射:                                    

每个学生都有一个地址,一对一;

数据库中t_student和t_address:

t_address:

Student.java 实体:

package com.cy.model;

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

    public Student(){

    }

    public Student(String name, Integer age){
        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 Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age
                + ", address=" + address + "]";
    }

}

Address.java 实体:

package com.cy.model;

public class Address {

    private Integer id;
    private String sheng;
    private String shi;
    private String qu;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getSheng() {
        return sheng;
    }
    public void setSheng(String sheng) {
        this.sheng = sheng;
    }
    public String getShi() {
        return shi;
    }
    public void setShi(String shi) {
        this.shi = shi;
    }
    public String getQu() {
        return qu;
    }
    public void setQu(String qu) {
        this.qu = qu;
    }
    @Override
    public String toString() {
        return "Address [id=" + id + ", sheng=" + sheng + ", shi=" + shi
                + ", qu=" + qu + "]";
    }

}

StudentMapper.java接口:

//查询学生,带地址
    @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",[email protected](select="com.cy.mapper.AddressMapper.findById"))
            }
    )
    public Student findStudentWithAddress(int id);

AddressMapper.java接口:

public interface AddressMapper {

    @Select("select * from t_address where id=#{id}")
    public Address findById(Integer id);

}

mybatis的实现是:在查找学生的时候,将addressId,传到AddressMapper.findById方法,根据这个addressId查找address;

测试代码:

@Test
    public void testFindStudentWithAddress() {
        logger.info("测试学生,带地址");
        Student student = studentMapper.findStudentWithAddress(15);
        System.out.println(student);
    }

console打印:

四、使用注解,一对多映射                                  

一个年级下有多个学生,多个学生属于一个年级,年级和学生是一对多;

Student.java:

package com.cy.model;

public class Student{
    private Integer id;
    private String name;
    private Integer age;
    private Address address;
    private Grade grade;

    public Student(){

    }

    public Student(String name, Integer age){
        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 Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public Grade getGrade() {
        return grade;
    }

    public void setGrade(Grade grade) {
        this.grade = grade;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age
                + ", address=" + address + ", grade=" + grade + "]";
    }

}

Grade.java:

package com.cy.model;

import java.util.List;

public class Grade {

    private Integer id;
    private String gradeName;
    private List<Student> students;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getGradeName() {
        return gradeName;
    }
    public void setGradeName(String gradeName) {
        this.gradeName = gradeName;
    }
    public List<Student> getStudents() {
        return students;
    }
    public void setStudents(List<Student> students) {
        this.students = students;
    }
    @Override
    public String toString() {
        return "Grade [id=" + id + ", gradeName=" + gradeName +"]";
    }

}

数据库中表,t_student:

t_grade:

1)根据id查找年级,将年级下的学生也查出来:

GradeMapper.java:

public interface GradeMapper {

    //根据id查找年级,将年级下的学生也查出来
    @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",[email protected](select="com.cy.mapper.StudentMapper.findStudentByGradeId"))
            }
    )
    public Grade findById(Integer id);
}

StudentMapper.java:

//根据年级查找学生
    @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",[email protected](select="com.cy.mapper.AddressMapper.findById"))
            }
    )
    public Student findStudentByGradeId(int gradeId);

测试代码:

//根据id查找年级,将年级下的学生也查出来
    @Test
    public void testFindGradeWithStudents() {
        logger.info("根据id查询年级(带学生)");
        Grade grade=gradeMapper.findById(1);
        System.out.println(grade);
        List<Student> studentList=grade.getStudents();
        for(Student student:studentList){
            System.out.println(student);
        }
    }

结果:

2)根据id查询学生,将年级信息也查出来:

StudentMapper.java:

//根据id查询学生带地址   和 年级
    @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",[email protected](select="com.cy.mapper.AddressMapper.findById")),
                @Result(column="gradeId",property="grade",[email protected](select="com.cy.mapper.GradeMapper.findById"))
            }
    )
    public Student findStudentWithAddressAndGrade(int id);

GradeMapper.java中的findById和上面1)中一样;

测试代码:

//根据id查询学生,带地址和年级
    @Test
    public void testSelectStudentWithAddressAndGrade() {
        logger.info("根据id查询学生(带地址、年级)");
        Student student=studentMapper.findStudentWithAddressAndGrade(1);
        System.out.println(student);
    }

打印结果:

时间: 2024-11-09 12:34:58

小峰mybatis(4)mybatis使用注解配置sql映射器的相关文章

Java Persistence with MyBatis 3(中文版) 第四章 使用注解配置SQL映射器

在上一章,我们看到了我们是怎样在映射器Mapper XML配置文件中配置映射语句的.MyBatis也支持使用注解来配置映射语句.当我们使用基于注解的映射器接口时,我们不再需要在XML配置文件中配置了.如果你愿意,你也可以同时使用基于XML和基于注解的映射语句. 本章将涵盖以下话题: l 在映射器Mapper接口上使用注解 l 映射语句 @Insert,@Update,@Delete,@SeelctStatements l 结果映射 一对一映射 一对多映射 l 动态SQL @SelectProvi

小峰mybatis(5)mybatis使用注解配置sql映射器--动态sql

一.使用注解配置映射器 动态sql: 用的并不是很多,了解下: Student.java 实体bean: package com.cy.model; public class Student{ private Integer id; private String name; private Integer age; public Student(){ } public Student(String name, Integer age){ this.name = name; this.age =

Java Persistence with MyBatis 3(中文版) 第三章 使用XML配置SQL映射器

关系型数据库和SQL是经受时间考验和验证的数据存储机制.和其他的ORM 框架如Hibernate不同,MyBatis鼓励开发者可以直接使用数据库,而不是将其对开发者隐藏,因为这样可以充分发挥数据库服务器所提供的SQL语句的巨大威力.与此同时,MyBaits消除了书写大量冗余代码的痛苦,它使使用SQL更容易. 在代码里直接嵌套SQL语句是很差的编码实践,并且维护起来困难.MyBaits使用了映射器配置文件或注解来配置SQL语句.在本章中,我们会看到具体怎样使用映射器配置文件来配置映射SQL语句.

SQL映射器Mapper接口(MyBatis)

SQL映射器Mapper接口 MyBatis基于代理机制,可以让我们无需再写Dao的实现.直接把以前的dao接口定义成符合规则的Mapper. 注意事项: 1.接口必须以Mapper结尾,名字是DomainMapper 2.mapper.xml文件要和Mapper接口建立关系,通过namespace:要能连接到Mapper接口   3.mapper.xml中写查询语句的标签的传入参数类型(parameterType).返回结果类型(resultType)必须和mapper接口中对应方法的传入参数

非注解的处理器映射器和适配器

在spring3.1之前使用org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping注解映射器. 在spring3.1之后使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping注解映射器. 在spring3.1之前使用org.springframework.web.servlet.mv

MyBatis数据库连接的基本使用-补充Mapper映射器

补充 Mapper映射器的使用: Mapper映射器,google添加.Mapper映射器是将mapper.xml中配置的sql id,parameterType和resultMap按照规则一一映射到接口中,后续MyBatis创建完接口实例后,可以直接调用对象中的方法操作数据库,其底层还是调用了sqlSession的 API (1)什么是Mapper映射器 符合映射文件要求的一个接口:Mybatis会生成符合该接口要求的对象 (2)接口要求 a 方法名要与mapper.xml配置文件中sql的i

【SpringMVC笔记】第四课 注解的处理器映射器和处理器适配器使用

一.注意点: 版本问题 spring3.2以前的版本,注解的映射器和适配器使用以下两个类. org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping.class org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.class 在新版本的源码中可以看到以下注释: 在3.2 包含及以后的版本中使用如

注解的处理器映射器和适配器

1, 配置注解映射器和适配器. <!--注解映射器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> <!--注解适配器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMa

基于maven的SpringMVC,Spring,MyBatis的全注解配置

首先创建maven项目 1.maven添加各种依赖包 <!-- 数据库连接池 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!-- Mybatis与Spring的包 --> <dependency>