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. springboot整合netty,多种启动netty的方式,展现bean得多种启动方法

    首先讲解下,spring中初始化加载问题: 很多时候,我们自己写的线程池,还有bean对象,还有其他的服务类,都可以通过,相关注解进行交给spring去管理,那么我们如何让nettyserver初始化 ...

  2. tomcat+nginx 单机部署多应用LINUX

    1.首先虚拟机上安装nginx 和tomcat,这里安装就不赘述了. nginx安装可以参考https://www.linuxidc.com/Linux/2016-09/134907.htm,相关配置 ...

  3. 使用IO流将数据库中数据生成一个文件,结果使用Notepad++打开部分数据结尾出现NUL

    场景描述: 项目中通过java代码中从数据库中查询一系列数据,对数据做相应处理,然后通过字符流将数据写如一个新生成的文件中,将该项目部署在linux服务器上,最后生成的文件拿到本地使用notepad+ ...

  4. 换了SSD发现plank也好了

    我的Dock用的是plank,很简单很好用.为什么不用Docky还有其他什么玩意儿呢?plank很简单很好用,资源占用很少,可以智能隐藏,you nearly can't feel it but yo ...

  5. PHP-在排序数组中查找元素的第一个和最后一个位置

    给定一个按照升序排列的整数数组 nums,和一个目标值 target.找出给定目标值在数组中的开始位置和结束位置. 你的算法时间复杂度必须是 O(log n) 级别. 如果数组中不存在目标值,返回 [ ...

  6. Android项目中实现native调用

    转载自搜狗测试公众号,本人学习使用,侵权删 最近小编在做公司输入法项目中java与native交互部分的测试,先简单学习了java代码调用native代码的实现原理,本次与大家一起分享jni协议,了解 ...

  7. 解决mybatisplus saveBatch 或者save 无法插入主键问题

    解决mybatisplus saveBatch 或者save 无法插入主键问题 通过跟踪源码后得出结论,由于插入的表的主键不是自增的,而是手动赋值的,所以在调用saveBatch 执行的sql语句是没 ...

  8. CSIC_716_20191225【HTML基础入门】

    HTTP协议 超文本传输协议HyperText Transfer Protocol 四大特性: 1.一次请求一次响应 2.基于TCP/IP协议,作用于应用层 3.无状态 4.无连接 数据格式: 1.请 ...

  9. Vue学习笔记【9】——Vue指令之v-for和key属性

    迭代数组(普通数组.对象数组) <ul> <li v-for="(item, i) in list">索引:{{i}} --- 姓名:{{item.name ...

  10. Shiro学习(19)动态URL权限限制

    用过spring Security的朋友应该比较熟悉对URL进行全局的权限控制,即访问URL时进行权限匹配:如果没有权限直接跳到相应的错误页面.Shiro也支持类似的机制,不过需要稍微改造下来满足实际 ...