mybatis 使用注解简化xml映射文件
目录
关于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映射文件的更多相关文章
- Mybatis中的Mapper.xml映射文件sql查询接收多个参数
我们都知道,在Mybatis中的Mapper.xml映射文件可以定制动态SQL,在dao层定义的接口中定义的参数传到xml文件中之后,在查询之前mybatis会对其进行动态解析,通常使用#{}接收 ...
- 解决 org.apache.ibatis.binding.BindingException: Invalid bound statement (not found) 以及MyBatis批量加载xml映射文件的方式
错误 org.apache.ibatis.binding.BindingException: Invalid bound statement (not found) 的出现,意味着项目需要xml文件来 ...
- Mybatis中Mapper的Xml映射文件中,除了常见的select|insert|updae|delete标签之外,还有哪些标签?
还有很多其他的标签,<resultMap>.<parameterMap>.<sql>.<include>.<selectKey>,加上动态s ...
- MyBatis 的 XML 映射文件使用说明
简介 文档参考地址:http://www.mybatis.org/mybatis-3/zh/index.html MyBatis 的真正强大在于它的映射语句,也是它的魔力所在.由于它的异常强大,映射器 ...
- 【spring boot】14.spring boot集成mybatis,注解方式OR映射文件方式AND pagehelper分页插件【Mybatis】pagehelper分页插件分页查询无效解决方法
spring boot集成mybatis,集成使用mybatis拖沓了好久,今天终于可以补起来了. 本篇源码中,同时使用了Spring data JPA 和 Mybatis两种方式. 在使用的过程中一 ...
- 精尽MyBatis源码分析 - MyBatis初始化(二)之加载Mapper接口与XML映射文件
该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...
- Mybatis学习--Mapper.xml映射文件
简介 Mapper.xml映射文件中定义了操作数据库的sql,每个sql是一个statement,映射文件是mybatis的核心. 映射文件中有很多属性,常用的就是parameterType(输入类型 ...
- mybatis学习------打包xml映射文件
编译mybatis时,idea不会将mybatis的xml映射文件一起打包进jar,即在编译好的jar包里缺少mybatis映射文件,导致网站加载失败 为解决这个问题,可在mybatis对应modul ...
- 5.7 Liquibase:与具体数据库独立的追踪、管理和应用数据库Scheme变化的工具。-mybatis-generator将数据库表反向生成对应的实体类及基于mybatis的mapper接口和xml映射文件(类似代码生成器)
一. liquibase 使用说明 功能概述:通过xml文件规范化维护数据库表结构及初始化数据. 1.配置不同环境下的数据库信息 (1)创建不同环境的数据库. (2)在resource/liquiba ...
随机推荐
- Sqlite操作帮助类
sqlite帮助类 using System; using System.Collections.Generic; using System.Linq; using System.Text; us ...
- Cookie的一点认识!
使用cookie的时间不短了,但是每次都是用一点查一点,也没有总结过.趁着项目不忙的间隙,总结一下.首先说为什么要使用cookie,什么是cookie cookie是用户访问一些网站后,浏览器生成的给 ...
- sql server去掉某个字段前后空格问题
数据通过页面表单保存到数据库,由于有个选项是一个树形的下拉框,导致保存的这个字段的数据前面有空格,在sql server中可以使用 SELECT LTRIM(RTRIM(BelongPartyCode ...
- Bootstrap方法之--排版、代码
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8& ...
- DIV中文字换行显示
居然第一次遇到这种问题,还想了半天到底是怎么回事,为什么明明div设置宽度了,里面的文字超过宽度后居然不换行. (1)word-break属性,可以让浏览器实现在任意位置换行. normal:使用浏览 ...
- Mysql 数据库常用配置命令
1.查看mysql数据库默认编码: mysql> show variables like "character%"; +--------------------------+ ...
- Python 使用Python远程连接并操作InfluxDB数据库
使用Python远程连接并操作InfluxDB数据库 by:授客 QQ:1033553122 实践环境 Python 3.4.0 CentOS 6 64位(内核版本2.6.32-642.el6.x86 ...
- Netty学习笔记(六) 简单的聊天室功能之WebSocket客户端开发实例
在之前的Netty相关学习笔记中,学习了如何去实现聊天室的服务段,这里我们来实现聊天室的客户端,聊天室的客户端使用的是Html5和WebSocket实现,下面我们继续学习. 创建客户端 接着第五个笔记 ...
- Linux 安装 powershell
linux 安装 powershell Intro powershell 已经推出了一个 Powershell Core, 版本号对应 Powershell 6.x,可以跨平台,支持 Linux 和 ...
- 使用sqlyog或者navicat连接mysql提示1862错误解决
mysql的bin目录下执行 mysqladmin -uroot -p password 依次输入旧密码.新密码.确认新密码 修改后重新使用sqlyog或navicat连接成功 问题解决!