主流开发还是使用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",one=@One(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",many=@Many(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",one=@One(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",one=@One(select="com.cy.mapper.AddressMapper.findById")),
@Result(column="gradeId",property="grade",one=@One(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);
}

打印结果:

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

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

    本章将涵盖以下话题: l 在映射器Mapper接口上使用注解 l 映射语句 @Insert,@Update,@Delete,@SeelctStatements l 结果映射 一对一映射 一对多映射 l ...

  2. MyBatis 3 使用注解配置SQL映射器

    l 在映射器Mapper接口上使用注解 l 映射语句 @Insert,@Update,@Delete,@SeelctStatements l 结果映射 一对一映射 一对多映射 l 动态SQL @Sel ...

  3. 使用注解配置SQL映射器

    在上一章,我们看到了我们是怎样在映射器Mapper XML配置文件中配置映射语句的.MyBatis也支持使用注解来配置映射语句.当我们使用基于注解的映射器接口时,我们不再需要在XML配置文件中配置了. ...

  4. Mybatis基于接口注解配置SQL映射器(一)

    上文已经讲解了基于XML配置的SQL映射器,在XML配置的基础上MyBatis提供了简单的Java注解,使得我们可以不配置XML格式的Mapper文件,也能方便的编写简单的数据库操作代码. Mybat ...

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

    一.使用注解配置映射器 动态sql: 用的并不是很多,了解下: Student.java 实体bean: package com.cy.model; public class Student{ pri ...

  6. Mybatis基于接口注解配置SQL映射器(二)

    Mybatis之增强型注解 MyBatis提供了简单的Java注解,使得我们可以不配置XML格式的Mapper文件,也能方便的编写简单的数据库操作代码.但是注解对动态SQL的支持一直差强人意,即使My ...

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

    关系型数据库和SQL是经受时间考验和验证的数据存储机制.和其他的ORM 框架如Hibernate不同,MyBatis鼓励开发者可以直接使用数据库,而不是将其对开发者隐藏,因为这样可以充分发挥数据库服务 ...

  8. Mybatis基于XML配置SQL映射器(二)

    Mybatis之XML注解 之前已经讲到通过 mybatis-generator 生成mapper映射接口和相关的映射配置文件: 下面我们将详细的讲解具体内容 首先我们新建映射接口文档  sysUse ...

  9. Mybatis基于XML配置SQL映射器(一)

    Durid和Mybatis开发环境搭建 SpringBoot搭建基于Spring+SpringMvc+Mybatis的REST服务(http://www.cnblogs.com/nbfujx/p/76 ...

随机推荐

  1. TMemo Ctrl + A

    http://delphi.about.com/od/adptips2004/a/bltip0804_4.htm Here's how to implement the code for the CT ...

  2. 系统session超时时间的设置

    一个网站系统:当你停止活动一段时间后,系统自动退出 三种方式设置: 1. 在server.xml中定义context时采用如下定义: <Context path="/livsorder ...

  3. Alpha阶段项目复审

    队名 优点 缺点 名次 大马猴队 出现BUG修复时间短:针对初期用户需求的分析缺点能够快速更正,针对用户痛点实现了功能:开发的过程中削减了无用的功能,源代码管理比较好,更改能够及时提交,相关成员都有参 ...

  4. rocketmq集群安装,配置,测试

    完整的安装包及demo请到百度云盘下载: 1.上传安装包 2.解压安装包 创建目录rocketmq mkdir -p /apps/install/rocketmq 解压到目录rocketmq tar ...

  5. SharePoint Word Service-PowerShell

    1. 配置转换进程 Set-SPWordConversionServiceApplication –Identity "Word Automation Services" –Act ...

  6. 利用 gulp 来合并seajs 的项目

    gulp-seajs-transport 和 gulp-seajs-concat这两个gulp插件 gulp-seajs-transpor 这个插件这样是给每个js模块 标示 模块名称 gulp-se ...

  7. 解决:People下面选择分享可见联系人,选择多个联系人后通过短信分享,短信中只显示一个联系人

    问题描述: [操作步骤]:People下导入导出中选择分享可见联系人,选择多个联系人后通过短信分享 [测试结果]:短信中只能显示一个联系人 [预期结果]:可以显示多个联系人 经过代码分析,从compo ...

  8. git添加本地项目到git

    1.切换到项目所在文件夹下:git int 2.git add -A 3.git commit -m '11' 4.git remote add origin https://github.com/g ...

  9. Jenkins自动化部署代码

    通过jenkins自动化部署项目代码可以大幅度节省打包上传部署的时间,提高开发测试的工作效率 ========== 完美的分割线 =========== 1.Jenkins是什么 1)Jenkins是 ...

  10. [LeetCode&Python] Problem 461. Hamming Distance

    The Hamming distance between two integers is the number of positions at which the corresponding bits ...