目录


关于mybatis注解

初次简单使用mybatis注解示例

利用注解实现指定映射

使用注解实现表间关联(1对1)


关于mybatis注解

  注解在java中特别常见,mybatis中也支持注解。

  mybatis的注解主要功能是:简化mapper.xml文件,简单的sql可以使用注解,而不用在取mapper.xml中写sql了,但是动态sql或者稍微复杂的sql,还得写在mapper.xml中。

  mybatis的注解和mapper.xml可以共存。

  需要注意:

  mybatis配置文件在加载映射文件或者接口的时候,是有点区别的。

  1、对于xml文件,可以使用:

<mapper resource="cn/ganlixin/mapper/XxxMapper.xml" />
<mapper url="file:///E:/mappers/XxxMapper.xml" />

  2、对于interface,可以使用:

<mapper class="cn.ganlixin.mapper.PersonMapper" />
<package name="cn.ganlixin.mapper" />

  

初次简单使用mybatis注解示例

  创建实体类:cn.ganlixin.pojo.Person.java

package cn.ganlixin.pojo;

import java.io.Serializable;

public class Person implements Serializable{
private int id;
private String name;
private int age;
//省略了无参构造方法、有参构造方法、setter、getter、toString
}

  

  创建interface:cn.ganlixin.mapper.PersonMapper.java

package cn.ganlixin.mapper;

import java.util.List;

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 cn.ganlixin.pojo.Person; public interface PersonMapper { @Select("select * from person where id=#{0}")
public Person selectPersonById(int id); @Select("select * from person")
public List<Person> selectAllPerson(); @Delete("delete from person where id=#{id}")
public int deleteOnePerson(Person person); @Insert("insert into person (id, name, age) values (default, #{name}, #{age})")
public int addPerson(Person person); @Update("update person set name=#{name} where id=#{id}")
public int updatePersonName(Person person);
}

  

  修改mybatis配置文件,加载该interface:

<?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="conf/db.properties"></properties> <settings>
<setting name="logImpl" value="log4J"></setting>
</settings> <typeAliases>
<package name="cn.ganlixin.pojo" />
</typeAliases> <environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
</dataSource>
</environment>
</environments> <mappers>
<!-- 一次只加载一个interface -->
<!-- <mapper class="cn.ganlixin.mapper.PersonMapper"></mapper> --> <!-- 一次性加载包下的所有interface -->
<package name="cn.ganlixin.mapper"></package>
</mappers>
</configuration>

  

  进行测试:

package cn.ganlixin.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import cn.ganlixin.mapper.PersonMapper;
import cn.ganlixin.pojo.Person; public class TestMybatis {
public static void main(String[] args) { try {
String resource = "conf/mybatis.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession(); PersonMapper mapper = session.getMapper(PersonMapper.class); Person person = mapper.selectPersonById(1);
System.out.println(person);
//---------------------------------------------------- List<Person> list = mapper.selectAllPerson();
for (Person p : list) {
System.out.println(p);
}
//---------------------------------------------------- int count = mapper.addPerson(new Person(3, "cccc", 55));
System.out.println(count);
//---------------------------------------------------- Person p = new Person();
p.setId(3);
p.setName("dddd");
count = mapper.updatePersonName(p);
System.out.println(count);
//---------------------------------------------------- count = mapper.deleteOnePerson(p);
System.out.println(count);
//---------------------------------------------------- session.commit();
session.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

  

利用注解实现指定映射

  假设上面的Person实体类中的属性名与数据库中person表中字段名不一一对应时,比如下面这样:

package cn.ganlixin.pojo;

import java.io.Serializable;

public class Person implements Serializable{
private int id1;
private String name1;
private int age1;
//省略了无参构造方法、有参构造方法、setter、getter、toString
}

  数据库中person表中的字段是id、name、age,显然与Person类的id1、name1、age1属性不符合。

  重新修改PersonMapper接口:

package cn.ganlixin.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.Select;
import org.apache.ibatis.annotations.Update; import cn.ganlixin.pojo.Person; public interface PersonMapper {
@Results(value={
@Result(id=true, column="id", property="id1"),
@Result(column="name", property="name1"),
@Result(column="age", property="age1")
})
@Select("select * from person where id=#{0}")
public Person selectPersonById(int id); // 需要多次配置@Results
@Results(value={
@Result(id=true, column="id", property="id1"),
@Result(column="name", property="name1"),
@Result(column="age", property="age1")
})
@Select("select * from person")
public List<Person> selectAllPerson(); // 对于增删改,属性作为参数时,传入的参数直接指定准确的属性名,不要用@Result
@Delete("delete from person where id=#{id1}")
public int deleteOnePerson(Person person); @Insert("insert into person (id, name, age) values (default, #{name1}, #{age1})")
public int addPerson(Person person); @Update("update person set name=#{name} where id=#{id1}")
public int updatePersonName(Person person);
}

  

  进行测试:

  测试代码与上一次的测试代码相同,并且测试结果也与上一次的测试结果相同。

使用注解实现表间关联(1对1)

  1对1,就以独生子为例吧,一个father只有一个son。

  创建实体类cn.ganlixin.pojo.Son.java

package cn.ganlixin.pojo;

public class Son {
private int id;
private String name; private int fid; // father id //省略了无参构造方法、有参构造方法、setter、getter、toString
}

  

  创建实体类cn.ganlixin.pojo.Father.java

package cn.ganlixin.pojo;

public class Father {
private int id;
private String name;
private Son son; // 包含一个son对象 //省略了无参构造方法、有参构造方法、setter、getter、toString
}

  

  创建cn.ganlixin.mapper.FatherMapper.java

package cn.ganlixin.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import cn.ganlixin.pojo.Father;

public interface FatherMapper {

	@Select("select f.id, f.name, s.id `son.id`, s.name `son.name`, s.fid `son.fid` "
+ "from father f left join son s on f.id=s.fid")
public List<Father> selectAll();
}

  

mybatis 使用注解简化xml映射文件的更多相关文章

  1. Mybatis中的Mapper.xml映射文件sql查询接收多个参数

    ​ 我们都知道,在Mybatis中的Mapper.xml映射文件可以定制动态SQL,在dao层定义的接口中定义的参数传到xml文件中之后,在查询之前mybatis会对其进行动态解析,通常使用#{}接收 ...

  2. 解决 org.apache.ibatis.binding.BindingException: Invalid bound statement (not found) 以及MyBatis批量加载xml映射文件的方式

    错误 org.apache.ibatis.binding.BindingException: Invalid bound statement (not found) 的出现,意味着项目需要xml文件来 ...

  3. Mybatis中Mapper的Xml映射文件中,除了常见的select|insert|updae|delete标签之外,还有哪些标签?

    还有很多其他的标签,<resultMap>.<parameterMap>.<sql>.<include>.<selectKey>,加上动态s ...

  4. MyBatis 的 XML 映射文件使用说明

    简介 文档参考地址:http://www.mybatis.org/mybatis-3/zh/index.html MyBatis 的真正强大在于它的映射语句,也是它的魔力所在.由于它的异常强大,映射器 ...

  5. 【spring boot】14.spring boot集成mybatis,注解方式OR映射文件方式AND pagehelper分页插件【Mybatis】pagehelper分页插件分页查询无效解决方法

    spring boot集成mybatis,集成使用mybatis拖沓了好久,今天终于可以补起来了. 本篇源码中,同时使用了Spring data JPA 和 Mybatis两种方式. 在使用的过程中一 ...

  6. 精尽MyBatis源码分析 - MyBatis初始化(二)之加载Mapper接口与XML映射文件

    该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...

  7. Mybatis学习--Mapper.xml映射文件

    简介 Mapper.xml映射文件中定义了操作数据库的sql,每个sql是一个statement,映射文件是mybatis的核心. 映射文件中有很多属性,常用的就是parameterType(输入类型 ...

  8. mybatis学习------打包xml映射文件

    编译mybatis时,idea不会将mybatis的xml映射文件一起打包进jar,即在编译好的jar包里缺少mybatis映射文件,导致网站加载失败 为解决这个问题,可在mybatis对应modul ...

  9. 5.7 Liquibase:与具体数据库独立的追踪、管理和应用数据库Scheme变化的工具。-mybatis-generator将数据库表反向生成对应的实体类及基于mybatis的mapper接口和xml映射文件(类似代码生成器)

    一. liquibase 使用说明 功能概述:通过xml文件规范化维护数据库表结构及初始化数据. 1.配置不同环境下的数据库信息 (1)创建不同环境的数据库. (2)在resource/liquiba ...

随机推荐

  1. C# 如何获取Url的host以及是否是http

    参考资料:https://sites.google.com/site/netcorenote/asp-net-core/get-scheme-url-host Example there's an g ...

  2. Predicate--入门简介

    说明:表示定义一组条件并确定指定对象是否符合这些条件的方法.此委托由 Array 和 List 类的几种方法使用,用于在集合中搜索元素. var predicate = new Predicate&l ...

  3. Acer宏碁笔记本触摸板失效解决方法

    打开windows设置,找到鼠标设置 之后,选择触摸板设置,将其开启 PS: 由于我是安装完驱动之后,才发现有这个触摸板设置的 如果找不到这个触摸板设置的哈,应该就是驱动安装完之后就有了 驱动的话去官 ...

  4. 从URL到看到网页的过程

    从我们输入URL并按下回车键到看到网页结果之间发生了什么?换句话说,一张网页,要经历怎样的过程,才能抵达用户面前?下面来从一些细节上面尝试一下探寻里面的秘密. 前言:键盘与硬件中断 说到输入URL,当 ...

  5. android集成twitter登录

    Twitter曾经举行了自己四年以来的第一场开发者大会.而这场名为“Flight”的大会,也是以后它的年度惯例. 这次大会的主题也完全围绕开发者进行.大会的焦点是一个名叫Fabric的新SDK,里面包 ...

  6. Kotlin入门(31)JSON字符串的解析

    json是App进行网络通信最常见的数据交互格式,Android也自带了json格式的处理工具包org.json,该工具包主要提供了JSONObject(json对象)与JSONArray(json数 ...

  7. java实现Windows记事本

    给大家分享下我之前的作品: 源文件下载: 链接:https://pan.baidu.com/s/1N45VsS9aVgmvhvYjRLxBrA  提取码:b9fg  源码: JF_Notpad.jav ...

  8. 【公众号系列】超详细SAP HANA JOB全解析

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[公众号系列]超详细SAP HANA JOB全解 ...

  9. mysql 的远程链接字符

    默认情况下,mysql只允许本地登录,如果要开启远程连接,则需要修改/etc/mysql/my.conf文件. 一.修改/etc/mysql/my.conf找到bind-address = 127.0 ...

  10. 一、Windows Server 2016 AD服务器搭建

    简介: AD是Active Directory的简写,中文称活动目录.活动目录(Active Directory)主要提供以下功能: 1)服务器及客户端计算机管理 2)用户服务 3)资源管理 4)桌面 ...