笔记54 Mybatis快速入门(五)
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快速入门(五)的更多相关文章
- MyBatis学习笔记(一)——MyBatis快速入门
转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4261895.html 一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优 ...
- 笔记56 Mybatis快速入门(七)
相关概念介绍(二) 6.一级缓存 <1>在一个session里查询相同id的数据 package mybatis.annotation; import java.io.IOExceptio ...
- 笔记50 Mybatis快速入门(一)
一.Mybatis简介 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis ...
- mybatis快速入门(五)
今天写写user表和orders表的mybatis的高级映射,一对一映射和一对多映射 1.创建一个orders.java文件 1.1一对一映射,一条订单对应一个用户 package cn.my.myb ...
- 笔记55 Mybatis快速入门(六)
相关概念介绍(一) 1.日志 有时候需要打印日志,知道mybatis执行了什么样的SQL语句,以便进行调试.这时,就需要开启日志,而mybatis自身是没有带日志的,使用的都是第三方日志,这里介绍如何 ...
- 笔记53 Mybatis快速入门(四)
动态SQL 1.if 假设需要对Product执行两条sql语句,一个是查询所有,一个是根据名称模糊查询.那么按照现在的方式,必须提供两条sql语句:listProduct和listProductBy ...
- 笔记52 Mybatis快速入门(三)
一.更多查询 1.模糊查询 修改Category.xml,提供listCategoryByName查询语句select * from category where name like concat(' ...
- 笔记51 Mybatis快速入门(二)
Mybatis的CRUD 1.修改配置文件Category.xml,提供CRUD对应的sql语句. <?xml version="1.0" encoding="UT ...
- MyBatis学习总结(一)——MyBatis快速入门
一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以 ...
随机推荐
- 暴力穷举zip、rar压缩文件的密码
生成密码的方式类似与时钟,末尾遍历完了第k位所有的字符,就让第k位的前一位到下一位字符,第k位回到第0个字符. 对python还不太熟悉,效率比较低,但是能破解简单的密码. import zipfil ...
- 算法竞赛模板 动态规划之背包DP
① 01背包 有n件物品和一个容量为v的背包.第i件物品的价值是c[i],体积是w[i].求解将哪些物品装入背包可使价值总和最大. 这是最基础的背包问题,特点是:每种物品仅有一件,可以选择放或不放. ...
- HTML CSS的中英文对照
python 大蟒蛇 downloads 下载 install 安装 customize 自定义 path 环境变量:路径 optional 可选的 feature 特性特点 documentatio ...
- stat - 打印信息节点(inode)内容
SYNOPSIS(总览) stat filename [filenames ... ] DESCRIPTION(描述) stat 打印出一个信息节点的内容,它们显示为对人可读的格式的stat(2). ...
- Java 连接池的工作原理
什么是连接? 连接,是我们的编程语言与数据库交互的一种方式.我们经常会听到这么一句话“数据库连接很昂贵“. 有人接受这种说法,却不知道它的真正含义.因此,下面我将解释它究竟是什么.[如果你已经知道了, ...
- Java连接ActiveMQ代码示例(Producer和Consumer)
import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; ...
- JSON.parse 解析json字符串时,遇字符串换行符,解析失败
今天遇到json字符串转对象时报错了,发现有个字符串有换行符,仔细找了原因. 结果是因为JSON.parse转json字符串时遇到一些特殊字符需要先转义,如图所示 然后尝试了各路大神介绍的办法,均不适 ...
- Python爬虫实战——反爬策略之代理IP【无忧代理】
一般情况下,我并不建议使用自己的IP来爬取网站,而是会使用代理IP. 原因很简单:爬虫一般都有很高的访问频率,当服务器监测到某个IP以过高的访问频率在进行访问,它便会认为这个IP是一只"爬虫 ...
- leetcode-按奇偶排序数组II
Python解决方法: class Solution(object): def sortArrayByParityII(self, A): j = 1 for i in xrange(0, len(A ...
- 【LeetCode 25】K 个一组翻转链表
题目链接 [题解] 模拟就好. 就k个k个节点地翻转. 每个节点都把next域指向它前面那个节点 修改完之后把这个节点前面的那个节点的next域改成这一段的最后一个节点. 然后把这一段最左边的那个节点 ...