Mybatis中注解的使用

1.XML方式的CRUD

新增加接口CategoryMapper ,并在接口中声明的方法上,加上注解对比配置文件Category.xml,其实就是把SQL语句从XML挪到了注解上来。

CategoryMapper.java

 package mybatis.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 mybatis.pojo.Category; public interface CategoryMapper {
@Insert("insert into category (name) values (#{name})")
public int add(Category category); @Delete("delete from category where id= #{id}")
public void delete(int id); @Select("select * from category where id= #{id}")
public Category get(int id); @Update("update category set name=#{name} where id=#{id}")
public int update(Category category); @Select("select * from category")
public List<Category> list();
}

在mybatis-config.xml中增加映射:

 <mapper class="mybatis.mapper.CategoryMapper"/>

测试:

 package mybatis.annotation;

 import java.io.IOException;
import java.io.InputStream;
import java.util.List; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import mybatis.mapper.CategoryMapper;
import mybatis.pojo.Category; public class testCRUD {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
CategoryMapper categoryMapper = session.getMapper(CategoryMapper.class);
add(categoryMapper);
// listAll(categoryMapper);
session.commit();
session.close(); } private static void update(CategoryMapper mapper) {
Category category = mapper.get(0);
category.setName("修改了的Category名称");
mapper.update(category);
listAll(mapper);
} private static void delete(CategoryMapper mapper) {
mapper.delete(2);
listAll(mapper);
} private static void add(CategoryMapper mapper) {
Category category = new Category();
category.setName("新增的Category");
mapper.add(category);
listAll(mapper);
} private static void get(CategoryMapper mapper) {
Category category = mapper.get(1);
System.out.println(category.getName());
} private static void listAll(CategoryMapper mapper) {
List<Category> cs = mapper.list();
for (Category c : cs) {
System.out.println(c.getName());
}
}
}

2.一对多

①查询所有Category,通过@Select注解获取Category类本身。@Results 通过@Result和@Many中调用ProductMapper.listByCategory()方法相结合,来获取一对多关系。

     @Select("select * from category")
@Results({ @Result(property = "id", column = "id"),
@Result(property = "products", javaType = List.class, column = "id", many = @Many(select = "mybatis.mapper.ProductMapper.listByCategory")) })
public List<Category> list2();

②新增接口ProductMapper
注解@Select用于根据分类id获取产品集合
@Select(" select * from product_ where cid = #{cid}")

 package mybatis.mapper;

 import java.util.List;

 import org.apache.ibatis.annotations.Select;

 import mybatis.pojo.Product;

 public interface ProductMapper {
@Select("select * from product where cid=#{cid}")
public List<Product> listByCategory(int cid);
}

③添加ProductMapper和CategoryMapper的映射

 <mapper class="mybatis.mapper.CategoryMapper"/>
<mapper class="mybatis.mapper.ProductMapper"/>

④结果:

3.多对一

①在CategoryMapper接口中提供get方法

     @Select("select * from category where id= #{id}")
public Category get(int id);

②在ProductMapper接口中提供list方法

 @Select("select * from product")
@Results({ @Result(property = "id", column = "id"), @Result(property = "name", column = "name"),
@Result(property = "price", column = "price"),
@Result(property = "category", column = "cid", one = @One(select = "mybatis.mapper.CategoryMapper.get")) })
public List<Product> list();

③测试

 package mybatis.annotation;

 import java.io.IOException;
import java.io.InputStream;
import java.util.List; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import mybatis.mapper.ProductMapper;
import mybatis.pojo.Product; public class testManyToOne { public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String resource = "mybatis-config.xml";
InputStream inputStream = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
ProductMapper productMapper = session.getMapper(ProductMapper.class); List<Product> products = productMapper.list();
for (Product product : products) {
System.out.println(product + "\t对应的分类是:\t" + product.getCategory().getName());
} session.commit();
session.close();
} }

4.多对多

①ProductMapper接口中,新增get方法。

     @Select("select * from product where id=#{id}")
public Product get(int id);

②新增OrderItemMapper,提供listByOrder方法。
这里会与Product建立多对一关系,一种商品可以出现在多个订单中。

 package mybatis.mapper;

 import java.util.List;

 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 mybatis.pojo.OrderItem; public interface OrderItemMapper {
@Select("select * from order_item where oid=#{oid}")
@Results({ @Result(property = "id", column = "id"), @Result(property = "number", column = "number"),
@Result(property = "product", column = "pid", one = @One(select = "mybatis.mapper.ProductMapper.get")) })
public List<OrderItem> listByOrder(int oid);
}

③新增OrderMapper,提供list方法,这里会与OrderItem建立一对多关系,一个订单中会有多个商品

 package mybatis.mapper;

 import java.util.List;

 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 mybatis.pojo.Order; public interface OrderMapper {
@Select("select * from order_")
@Results({ @Result(property = "id", column = "id"), @Result(property = "code", column = "code"),
@Result(property = "orderItems", column = "id", javaType = List.class, many = @Many(select = "mybatis.mapper.OrderItemMapper.listByOrder")) })
public List<Order> list();
}

④修改mybatis-config.xml,增加新的映射。

 <mapper class="mybatis.mapper.OrderMapper"/>
<mapper class="mybatis.mapper.OrderItemMapper"/>

⑤测试

 package mybatis.annotation;

 import java.io.IOException;
import java.io.InputStream;
import java.util.List; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import mybatis.mapper.OrderMapper;
import mybatis.pojo.Order;
import mybatis.pojo.OrderItem; public class testManyToMany { public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String resource = "mybatis-config.xml";
InputStream inputStream = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
OrderMapper orderMapper = session.getMapper(OrderMapper.class);
listOrder(orderMapper);
session.commit();
session.close();
} private static void listOrder(OrderMapper orderMapper) {
List<Order> orders = orderMapper.list();
for (Order order : orders) {
System.out.println(order.getCode());
List<OrderItem> orderItems = order.getOrderItems();
for (OrderItem orderItem : orderItems) {
System.out.format("\t%s\t%f\t%d%n", orderItem.getProduct().getName(), orderItem.getProduct().getPrice(),
orderItem.getNumber());
}
}
} }

5.动态SQL语句

把手写SQL语句的注解CRUD(1),修改为动态SQL语句方式。

①新增CategoryDynaSqlProvider,提供CRUD对应的SQL语句。这里的SQL语句使用SQL类的方式构建。

 package mybatis.dynasql;

 import org.apache.ibatis.jdbc.SQL;

 public class CategoryDynaSqlProvider {
public String list() {
return new SQL().SELECT("*").FROM("category").toString();
} public String get() {
return new SQL().SELECT("*").FROM("category").WHERE("id=#{id}").toString();
} public String add() {
return new SQL().INSERT_INTO("category").VALUES("name", "#{name}").toString();
} public String update() {
return new SQL().UPDATE("category").SET("name=#{name}").WHERE("id=#{id}").toString();
} public String delete() {
return new SQL().DELETE_FROM("category").WHERE("id=#{id}").toString();
}
}

②新增CategoryMapperDynaSQL.java

把本来是手写SQL的CategoryMapper接口,修改为注解引用CategoryDynaSqlProvider类的方式。
例如:增加本来是手写SQL语句的

     @Insert("insert into category (name) values (#{name})")
public int add(Category category);

修改为了注解@InsertProvider配合CategoryDynaSqlProvider的add方法:

 @InsertProvider(type = CategoryMapperDynaSQL.class, method = "add")
public int add(Category category);
 package mybatis.mapper;

 import java.util.List;

 import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider; import mybatis.pojo.Category; public interface CategoryMapperDynaSQL {
@InsertProvider(type = CategoryMapperDynaSQL.class, method = "add")
public int add(Category category); @DeleteProvider(type = CategoryMapperDynaSQL.class, method = "delete")
public void delete(int id); @SelectProvider(type = CategoryMapperDynaSQL.class, method = "get")
public Category get(int id); @UpdateProvider(type = CategoryMapperDynaSQL.class, method = "update")
public int update(Category category); @SelectProvider(type = CategoryMapperDynaSQL.class, method = "list")
public List<Category> list(); }

③测试

 package mybatis.annotation;

 import java.io.IOException;
import java.io.InputStream;
import java.util.List; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import mybatis.mapper.CategoryMapperDynaSQL;
import mybatis.pojo.Category; public class testCRUDDynaSQL {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
CategoryMapperDynaSQL categoryMapper = session.getMapper(CategoryMapperDynaSQL.class);
// add(categoryMapper);
// get(categoryMapper);
listAll(categoryMapper);
session.commit();
session.close(); } private static void update(CategoryMapperDynaSQL mapper) {
Category category = mapper.get(0);
category.setName("修改了的Category名称");
mapper.update(category);
listAll(mapper);
} private static void delete(CategoryMapperDynaSQL mapper) {
mapper.delete(2);
listAll(mapper);
} private static void add(CategoryMapperDynaSQL mapper) {
Category category = new Category();
category.setName("新增的Category");
mapper.add(category);
listAll(mapper);
} private static void get(CategoryMapperDynaSQL mapper) {
Category category = mapper.get(1);
System.out.println(category.getName());
} private static void listAll(CategoryMapperDynaSQL mapper) {
List<Category> cs = mapper.list();
for (Category c : cs) {
System.out.println(c.getName());
}
}
}

笔记54 Mybatis快速入门(五)的更多相关文章

  1. MyBatis学习笔记(一)——MyBatis快速入门

    转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4261895.html 一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优 ...

  2. 笔记56 Mybatis快速入门(七)

    相关概念介绍(二) 6.一级缓存 <1>在一个session里查询相同id的数据 package mybatis.annotation; import java.io.IOExceptio ...

  3. 笔记50 Mybatis快速入门(一)

    一.Mybatis简介 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis ...

  4. mybatis快速入门(五)

    今天写写user表和orders表的mybatis的高级映射,一对一映射和一对多映射 1.创建一个orders.java文件 1.1一对一映射,一条订单对应一个用户 package cn.my.myb ...

  5. 笔记55 Mybatis快速入门(六)

    相关概念介绍(一) 1.日志 有时候需要打印日志,知道mybatis执行了什么样的SQL语句,以便进行调试.这时,就需要开启日志,而mybatis自身是没有带日志的,使用的都是第三方日志,这里介绍如何 ...

  6. 笔记53 Mybatis快速入门(四)

    动态SQL 1.if 假设需要对Product执行两条sql语句,一个是查询所有,一个是根据名称模糊查询.那么按照现在的方式,必须提供两条sql语句:listProduct和listProductBy ...

  7. 笔记52 Mybatis快速入门(三)

    一.更多查询 1.模糊查询 修改Category.xml,提供listCategoryByName查询语句select * from category where name like concat(' ...

  8. 笔记51 Mybatis快速入门(二)

    Mybatis的CRUD 1.修改配置文件Category.xml,提供CRUD对应的sql语句. <?xml version="1.0" encoding="UT ...

  9. MyBatis学习总结(一)——MyBatis快速入门

    一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以 ...

随机推荐

  1. su 和 su - 命令有何不同

    su命令和su -命令最大的本质区别就是:前者只是切换了root身份,但Shell环境仍然是普通用户的Shell:而后者连用户和Shell环境一起切换成root身份了.只有切换了Shell环境才不会出 ...

  2. 学习JS基本数据类型与对象的valueOf方法

    https://blog.csdn.net/licheng11403080324/article/details/60128090 https://yq.aliyun.com/articles/399 ...

  3. Spring学习笔记(4)——IoC学习

    IoC理论的背景我们都知道,在采用面向对象方法设计的软件系统中,它的底层实现都是由N个对象组成的,所有的对象通过彼此的合作,最终实现系统的业务逻辑. 图1:软件系统中耦合的对象 如果我们打开机械式手表 ...

  4. C 语言sizeof运算符

    #include<stdio.h> int main() { ; ); ; int size3 = sizeof a; int size4 = sizeof(a); int size5 = ...

  5. enovia PLM : add new value to SPEO

    Solution: Modify LUX_SPEO attribute in PLM Modify D_SPEO attribute in SAP , Login sap system F3 Tcod ...

  6. 56. Map(双列集合)

    在生活中有些数据是以映射关系存在的,也就是成对出现的,比如:老公  老婆(key-->value) 双列集合:-------------------| Map    如果是实现了Map接口的集合 ...

  7. 简单API接口签名验证

    前言 后端在写对外的API接口时,一般会对参数进行签名来保证接口的安全性,在设计签名算法的时候,主要考虑的是这几个问题: 1. 请求的来源是否合法 2. 请求参数是否被篡改 3. 请求的唯一性 我们的 ...

  8. Collections 工具类常见方法

    Collections 工具类常用方法: 排序 查找,替换操作 同步控制(不推荐,需要线程安全的集合类型时请考虑使用 JUC 包下的并发集合) 排序操作 void reverse(List list) ...

  9. 「题解」:$Smooth$

    问题 A: Smooth 时间限制: 1 Sec  内存限制: 512 MB 题面 题面谢绝公开. 题解 维护一个队列,开15个指针,对应前15个素数. 对于每一次添加数字,暴扫15个指针,将指针对应 ...

  10. wmic命令用法小例

    wmic就是wmic.exe,位于windows目录底下,是一个命令行程序.WMIC可以以两种模式执行:交互模式(Interactive mode)和非交互模式(Non-Interactive mod ...