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. RK3288 控制usb摄像头补光GPIO

    正常可以通过添加dts配置,再从设备树中读取gpio号,在这里为了简单,直接使用GPIO号,先通过终端测试gpio, 系统自带GPIO控制驱动: 内核已经自带了通用GPIO驱动,可以直接在用户空间操作 ...

  2. css负边距之详解(子绝父相)

    来源 | http://segmentfault.com 原文 |  The Definitive Guide to Using Negative Margins   自从1998年CSS2作为推荐以 ...

  3. Spring Boot 2.0 常见问题总结(二)

    使用 IDEA 生成 POJO 实体类 a. 使用 idea 连接上需要操作的数据库. b. 选中要生成实体类的数据库表:右键 ---> Scripted Extensions ---> ...

  4. 调试Android有什么错误

    项目目录的cmd调试查看有什么错误 gradlew processDebugManifest --stacktrace

  5. js获取地址栏的参数

    //获取url参数 window.getParam = function(url, id) { url = url+ ""; var regstr = "/(\\?|\\ ...

  6. HTML标签分类总结

    块级元素和行内元素块级元素address - 地址blockquote - 块引用center - 举中对齐块dir - 目录列表div - 常用块级容易,也是css layout的主要标签dl - ...

  7. 【转】SpringMVC整合websocket实现消息推送及触发

    1.创建websocket握手协议的后台 (1)HandShake的实现类 /** *Project Name: price *File Name:    HandShake.java *Packag ...

  8. PHP ftp_connect() 函数

    定义和用法 ftp_connect() 函数打开 FTP 连接. 当连接打开后,您就可以通过服务器来运行 FTP 函数了. 语法 ftp_connect(host,port,timeout) 参数 描 ...

  9. PHP的开源产品discuz

    首先就是discuz,用起来真的是特别的好用,搭建的网站真的非常美观 尤其是用起来之后,我发现功能真的是太强大了,不用到处编写代码,调试什么 只需要把精力放在做产品上就可以了,我很好奇为什么会这么强大 ...

  10. 模拟+双指针——cf1244E

    排一遍序然后用l,r指针进行移动,每次移动的是靠1,或靠n更近的那个指针 #include<bits/stdc++.h> using namespace std; typedef long ...