博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
笔记54 Mybatis快速入门(五)
阅读量:4948 次
发布时间:2019-06-11

本文共 12875 字,大约阅读时间需要 42 分钟。

Mybatis中注解的使用

1.XML方式的CRUD

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

CategoryMapper.java

1 package mybatis.mapper; 2  3 import java.util.List; 4  5 import org.apache.ibatis.annotations.Delete; 6 import org.apache.ibatis.annotations.Insert; 7 import org.apache.ibatis.annotations.Select; 8 import org.apache.ibatis.annotations.Update; 9 10 import mybatis.pojo.Category;11 12 public interface CategoryMapper {13     @Insert("insert into category (name) values (#{name})")14     public int add(Category category);15 16     @Delete("delete from category where id= #{id}")17     public void delete(int id);18 19     @Select("select * from category where id= #{id}")20     public Category get(int id);21 22     @Update("update category set name=#{name} where id=#{id}")23     public int update(Category category);24 25     @Select("select * from category")26     public List
list();27 }

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

1 

测试:

1 package mybatis.annotation; 2  3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.List; 6  7 import org.apache.ibatis.session.SqlSession; 8 import org.apache.ibatis.session.SqlSessionFactory; 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;10 11 import mybatis.mapper.CategoryMapper;12 import mybatis.pojo.Category;13 14 public class testCRUD {15     public static void main(String[] args) throws IOException {16         String resource = "mybatis-config.xml";17         InputStream inputStream = org.apache.ibatis.io.Resources.getResourceAsStream(resource);18         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);19         SqlSession session = sqlSessionFactory.openSession();20         CategoryMapper categoryMapper = session.getMapper(CategoryMapper.class);21         add(categoryMapper);22         // listAll(categoryMapper);23         session.commit();24         session.close();25 26     }27 28     private static void update(CategoryMapper mapper) {29         Category category = mapper.get(0);30         category.setName("修改了的Category名称");31         mapper.update(category);32         listAll(mapper);33     }34 35     private static void delete(CategoryMapper mapper) {36         mapper.delete(2);37         listAll(mapper);38     }39 40     private static void add(CategoryMapper mapper) {41         Category category = new Category();42         category.setName("新增的Category");43         mapper.add(category);44         listAll(mapper);45     }46 47     private static void get(CategoryMapper mapper) {48         Category category = mapper.get(1);49         System.out.println(category.getName());50     }51 52     private static void listAll(CategoryMapper mapper) {53         List
cs = mapper.list();54 for (Category c : cs) {55 System.out.println(c.getName());56 }57 }58 }

2.一对多

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

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

②新增接口ProductMapper

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

1 package mybatis.mapper; 2  3 import java.util.List; 4  5 import org.apache.ibatis.annotations.Select; 6  7 import mybatis.pojo.Product; 8  9 public interface ProductMapper {10     @Select("select * from product where cid=#{cid}")11     public List
listByCategory(int cid);12 }

③添加ProductMapper和CategoryMapper的映射

1 
2

④结果:

3.多对一

①在CategoryMapper接口中提供get方法

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

②在ProductMapper接口中提供list方法

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

③测试

1 package mybatis.annotation; 2  3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.List; 6  7 import org.apache.ibatis.session.SqlSession; 8 import org.apache.ibatis.session.SqlSessionFactory; 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;10 11 import mybatis.mapper.ProductMapper;12 import mybatis.pojo.Product;13 14 public class testManyToOne {15 16     public static void main(String[] args) throws IOException {17         // TODO Auto-generated method stub18         String resource = "mybatis-config.xml";19         InputStream inputStream = org.apache.ibatis.io.Resources.getResourceAsStream(resource);20         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);21         SqlSession session = sqlSessionFactory.openSession();22         ProductMapper productMapper = session.getMapper(ProductMapper.class);23 24         List
products = productMapper.list();25 for (Product product : products) {26 System.out.println(product + "\t对应的分类是:\t" + product.getCategory().getName());27 }28 29 session.commit();30 session.close();31 }32 33 }

4.多对多

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

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

②新增OrderItemMapper,提供listByOrder方法。

这里会与Product建立多对一关系,一种商品可以出现在多个订单中。

1 package mybatis.mapper; 2  3 import java.util.List; 4  5 import org.apache.ibatis.annotations.One; 6 import org.apache.ibatis.annotations.Result; 7 import org.apache.ibatis.annotations.Results; 8 import org.apache.ibatis.annotations.Select; 9 10 import mybatis.pojo.OrderItem;11 12 public interface OrderItemMapper {13     @Select("select * from order_item where oid=#{oid}")14     @Results({ @Result(property = "id", column = "id"), @Result(property = "number", column = "number"),15             @Result(property = "product", column = "pid", one = @One(select = "mybatis.mapper.ProductMapper.get")) })16     public List
listByOrder(int oid);17 }

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

1 package mybatis.mapper; 2  3 import java.util.List; 4  5 import org.apache.ibatis.annotations.Many; 6 import org.apache.ibatis.annotations.Result; 7 import org.apache.ibatis.annotations.Results; 8 import org.apache.ibatis.annotations.Select; 9 10 import mybatis.pojo.Order;11 12 public interface OrderMapper {13     @Select("select * from order_")14     @Results({ @Result(property = "id", column = "id"), @Result(property = "code", column = "code"),15             @Result(property = "orderItems", column = "id", javaType = List.class, many = @Many(select = "mybatis.mapper.OrderItemMapper.listByOrder")) })16     public List
list();17 }

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

1 
2

⑤测试

1 package mybatis.annotation; 2  3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.List; 6  7 import org.apache.ibatis.session.SqlSession; 8 import org.apache.ibatis.session.SqlSessionFactory; 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;10 11 import mybatis.mapper.OrderMapper;12 import mybatis.pojo.Order;13 import mybatis.pojo.OrderItem;14 15 public class testManyToMany {16 17     public static void main(String[] args) throws IOException {18         // TODO Auto-generated method stub19         String resource = "mybatis-config.xml";20         InputStream inputStream = org.apache.ibatis.io.Resources.getResourceAsStream(resource);21         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);22         SqlSession session = sqlSessionFactory.openSession();23         OrderMapper orderMapper = session.getMapper(OrderMapper.class);24         listOrder(orderMapper);25         session.commit();26         session.close();27     }28 29     private static void listOrder(OrderMapper orderMapper) {30         List
orders = orderMapper.list();31 for (Order order : orders) {32 System.out.println(order.getCode());33 List
orderItems = order.getOrderItems();34 for (OrderItem orderItem : orderItems) {35 System.out.format("\t%s\t%f\t%d%n", orderItem.getProduct().getName(), orderItem.getProduct().getPrice(),36 orderItem.getNumber());37 }38 }39 }40 41 }

5.动态SQL语句

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

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

1 package mybatis.dynasql; 2  3 import org.apache.ibatis.jdbc.SQL; 4  5 public class CategoryDynaSqlProvider { 6     public String list() { 7         return new SQL().SELECT("*").FROM("category").toString(); 8     } 9 10     public String get() {11         return new SQL().SELECT("*").FROM("category").WHERE("id=#{id}").toString();12     }13 14     public String add() {15         return new SQL().INSERT_INTO("category").VALUES("name", "#{name}").toString();16     }17 18     public String update() {19         return new SQL().UPDATE("category").SET("name=#{name}").WHERE("id=#{id}").toString();20     }21 22     public String delete() {23         return new SQL().DELETE_FROM("category").WHERE("id=#{id}").toString();24     }25 }

②新增CategoryMapperDynaSQL.java

把本来是手写SQL的CategoryMapper接口,修改为注解引用CategoryDynaSqlProvider类的方式。

例如:增加本来是手写SQL语句的

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

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

1 @InsertProvider(type = CategoryMapperDynaSQL.class, method = "add")2 public int add(Category category);
1 package mybatis.mapper; 2  3 import java.util.List; 4  5 import org.apache.ibatis.annotations.DeleteProvider; 6 import org.apache.ibatis.annotations.InsertProvider; 7 import org.apache.ibatis.annotations.SelectProvider; 8 import org.apache.ibatis.annotations.UpdateProvider; 9 10 import mybatis.pojo.Category;11 12 public interface CategoryMapperDynaSQL {13     @InsertProvider(type = CategoryMapperDynaSQL.class, method = "add")14     public int add(Category category);15 16     @DeleteProvider(type = CategoryMapperDynaSQL.class, method = "delete")17     public void delete(int id);18 19     @SelectProvider(type = CategoryMapperDynaSQL.class, method = "get")20     public Category get(int id);21 22     @UpdateProvider(type = CategoryMapperDynaSQL.class, method = "update")23     public int update(Category category);24 25     @SelectProvider(type = CategoryMapperDynaSQL.class, method = "list")26     public List
list();27 28 }

③测试

 

1 package mybatis.annotation; 2  3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.List; 6  7 import org.apache.ibatis.session.SqlSession; 8 import org.apache.ibatis.session.SqlSessionFactory; 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;10 11 import mybatis.mapper.CategoryMapperDynaSQL;12 import mybatis.pojo.Category;13 14 public class testCRUDDynaSQL {15     public static void main(String[] args) throws IOException {16         String resource = "mybatis-config.xml";17         InputStream inputStream = org.apache.ibatis.io.Resources.getResourceAsStream(resource);18         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);19         SqlSession session = sqlSessionFactory.openSession();20         CategoryMapperDynaSQL categoryMapper = session.getMapper(CategoryMapperDynaSQL.class);21         // add(categoryMapper);22         // get(categoryMapper);23         listAll(categoryMapper);24         session.commit();25         session.close();26 27     }28 29     private static void update(CategoryMapperDynaSQL mapper) {30         Category category = mapper.get(0);31         category.setName("修改了的Category名称");32         mapper.update(category);33         listAll(mapper);34     }35 36     private static void delete(CategoryMapperDynaSQL mapper) {37         mapper.delete(2);38         listAll(mapper);39     }40 41     private static void add(CategoryMapperDynaSQL mapper) {42         Category category = new Category();43         category.setName("新增的Category");44         mapper.add(category);45         listAll(mapper);46     }47 48     private static void get(CategoryMapperDynaSQL mapper) {49         Category category = mapper.get(1);50         System.out.println(category.getName());51     }52 53     private static void listAll(CategoryMapperDynaSQL mapper) {54         List
cs = mapper.list();55 for (Category c : cs) {56 System.out.println(c.getName());57 }58 }59 }

 

转载于:https://www.cnblogs.com/lyj-gyq/p/9241110.html

你可能感兴趣的文章
Git忽略已经被版本控制的文件(添加.gitignore不会起作用)
查看>>
airprobe: gsm-tvoid : gsm_scan.py problem part1
查看>>
uva 11800 - Determine the Shape
查看>>
String painter (区间dp)
查看>>
make string from macro in C language
查看>>
layui [记录]
查看>>
JavaScript 闭包的例子
查看>>
发送curl请求的函数
查看>>
交换排序算法---冒泡排序与快速排序
查看>>
Git安装及创建版本库
查看>>
ubuntu操作系统以及开发环境的安装
查看>>
动态规划之01背包
查看>>
解决Docker容器时区及时间不同步问题
查看>>
Mybatis学习(一)
查看>>
centos6.9下 svn 1.7.10版本 编译安装
查看>>
poj3126 Prime Path 广搜bfs
查看>>
C# GET 和 SET作用
查看>>
CentOS系统日志
查看>>
CodeForces 297D Color the Carpet (脑补题)
查看>>
Android开发之蓝牙(Bluetooth)操作(二)--修改本机蓝牙设备的可见性,并扫描周围可用的蓝牙设备...
查看>>