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. Groovy学习:第四章 Groovy特性深入

    作者:chszs 1. 断言 Java开发者常常使用JUnit或TestNG做单元测试,所以对断言是很清楚的.断言是用于验证假设的条件是否为真.在Groovy的断言中,如果假设的条件不为真,那么就会抛 ...

  2. 微信小程序の微信js

    一.Javascript简介 二.nodejs中的jscript nodejs表示谷歌基于v8引擎的一门后端语言, ECMA表示ECMA262标准的基本js,native表示nodejs本身的一些包, ...

  3. 2019-8-31-gif-格式

    title author date CreateTime categories gif 格式 lindexi 2019-08-31 16:55:59 +0800 2018-2-13 17:23:3 + ...

  4. phpass类加密算法

    客户说用md5加密容易被破解,要求使用bcrypt加密,经搜索发现password_hash函数可以轻松对密码实现加盐加密,比md5更安全,缺点是运行慢. phpass是一个开源类库,它可以让我们更方 ...

  5. Delphi Close、Halt、terminate、ExitProcess的区别

    Close:1.只关闭本窗体2.当Close是一个主窗体时,程序会退出.3.Close会发生FormClose事件,FormCloseQuery事件4.主窗体close以后程序就Application ...

  6. Vue学习笔记【7】——Vue指令之v-model和双向数据绑定

    v-model是唯一可以实现双向数据绑定的vue指令 单向数据绑定:修改内存中的数据,页面上同步更改.v-bind <!-- v-bind 只能实现数据的单向绑定,从 M 自动绑定到 V, 无法 ...

  7. 【Flutter学习】基本组件之文本组件Text

    一,概述 文本组件(Text)负责显示文本和定义显示样式, 二,继承关系 Object > Diagnosticable > DiagnosticableTree > Widget ...

  8. Zookeeper集群介绍及其搭建

    1 Zookeeper集群简介 1为什么搭建Zookeeper集群 大部分分布式应用需要一个主控.协调器或者控制器来管理物理分布的子进程.目前,大多数都要开发私有的协调程序,缺乏一个通用机制,协调程序 ...

  9. Linux下使用java获取cpu、内存使用率

    原文地址:http://www.voidcn.com/article/p-yehrvmep-uo.html 思路如下:Linux系统中可以用top命令查看进程使用CPU和内存情况,通过Runtime类 ...

  10. Nginx 配置参数

    1 Proxy_send_timeout 定义后端在多久的时间内必须返回完所有的数据给Nginx. 2 Proxy_read_timeout