学习目的:在使用配置文件实现CURD的基础上,学会使用注解方式实现CURD。
Part 1
新建一个Mapper,在相应的增删改查的方法上添加相应的注释以及SQL语句。与普通方法相比,就是讲普通方法中的SQL语句移到了这个Mapper中。
package cn.vaefun.mapper;
import cn.vaefun.pojo.Category;
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 java.util.List;
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();
}
Part 2
配置mybatis-config.xml,新增对CategoryMapper的映射。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="cn.vaefun.pojo"/>
<!-- 扫描该包下的类
使得在后续配置文件pojo.xml中使用resultType的时候,可以直接使用Category,
而不必写全cn.vaefun.pojo.Category-->
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/vaefun_mybatis?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="cn/vaefun/pojo/pojo.xml"/>
<mapper resource="cn/vaefun/pojo/Product.xml"/>
<mapper resource="cn/vaefun/pojo/Order.xml"/>
<mapper resource="cn/vaefun/pojo/OrderItem.xml"/>
<mapper class="cn.vaefun.mapper.CategoryMapper"/>
</mappers>
</configuration>
Part 3
测试代码块(下面主类的后四个方法),需要注意的是要先调用CategoryMapper mapper = session.getMapper(CategoryMapper.class);,通过类名获取到mapper:
package cn.vaefun.test;
import cn.vaefun.mapper.CategoryMapper;
import cn.vaefun.pojo.Category;
import cn.vaefun.pojo.Order;
import cn.vaefun.pojo.OrderItem;
import cn.vaefun.pojo.Product;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestMybatis {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session=sqlSessionFactory.openSession();
CategoryMapper mapper = session.getMapper(CategoryMapper.class);
//insertCategory(session);
//deleteCategory(session);
//getCategory(session);
//updateCategory(session);
//listAll(session);
//listCategoryByName(session);
//listCategoryByIdAndName(session);
//listCategory(session);
//listProductNTo1(session);
//addOrederItem(session);
//deleteOrderItem(session);
//listOrder(session);
//updateProduct(session);
//listAllProduct(session);
//listProductByName(session);
//addCategory(mapper);
//deleteCategory(mapper);
updateCategory(mapper);
session.commit();
session.close();
}
/**
* 显示所有
* @param session
*/
public static void listAll(SqlSession session){
List<Category> cs=session.selectList("listCategory2");
for (Category c : cs) {
System.out.println(c.getId()+"\t"+c.getName());
}
// List<Product> products=session.selectList("listProduct");
// for (Product p : products) {
// System.out.println(p.getId());
// System.out.println(p.getName());
// System.out.println(p.getPrice());
// }
}
/**
* 添加
* @param session
*/
public static void insertCategory(SqlSession session){
Category c = new Category();
c.setName("这是insert的Category");
c.setId(5);
session.insert("addCategory",c);
}
/**
* 删除
* @param session
*/
public static void deleteCategory(SqlSession session){
Category c = new Category();
c.setId(5);
session.delete("deleteCategory",c);
}
/**
* 查找
* @param session
*/
public static void getCategory(SqlSession session){
Category c = session.selectOne("getCategory",3);
System.out.println(c.getName()+c.getId());
}
/**
* 修改
* @param session
*/
public static void updateCategory(SqlSession session){
Category c = session.selectOne("getCategory",4);
c.setName("修改过的Category");
session.update("updateCategory",c);
}
/**
* 模糊查找:%cat%
* @param session
*/
public static void listCategoryByName(SqlSession session){
List<Category> categoryList = session.selectList("listCategoryByName","cat");
for (Category c :
categoryList) {
System.out.println(c.getName());
}
}
/**
* 多条件查询
* @param session
*/
public static void listCategoryByIdAndName(SqlSession session){
Map map = new HashMap();
map.put("id",1);
map.put("name","cat");
List<Category> categoryList = session.selectList("listCategoryByIdAndName",map);
for (Category c :
categoryList) {
System.out.println(c.getId()+"\t"+c.getName());
}
}
/**
* 一对多
*/
public static void listCategory(SqlSession session){
List<Category> cs = session.selectList("listCategoryP");
for (Category c : cs) {
System.out.println(c);
List<Product> ps = c.getProducts();
for (Product p : ps) {
System.out.println("\t"+p);
}
}
}
/**
* 多对一查询
* @param session
*/
public static void listProductNTo1(SqlSession session){
List<Product> productList = session.selectList("listProductNTo1");
for (Product p :
productList) {
System.out.println(p+"对应的分类是\t"+p.getCategory());
}
}
/**
* 多对多查询
* @param session
*/
public static void listOrder(SqlSession session){
List<Order> orders = session.selectList("listOrder");
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());
}
}
}
/**
* 添加一个OrderItem
* @param session
*/
public static void addOrederItem(SqlSession session){
Order order = session.selectOne("getOrder",1);
Product product = session.selectOne("getProduct",6);
OrderItem orderItem = new OrderItem();
orderItem.setProduct(product);
orderItem.setOrder(order);
orderItem.setNumber(109);
session.insert("addOrderItem",orderItem);
}
/**
* 删除OrderItem
* @param session
*/
public static void deleteOrderItem(SqlSession session){
Order order = session.selectOne("getOrder",1);
Product product = session.selectOne("getProduct",6);
OrderItem orderItem = new OrderItem();
orderItem.setOrder(order);
orderItem.setProduct(product);
session.delete("deleteOrderItem",orderItem);
}
/**
* 查询所有的Product
* @param session
*/
public static void listAllProduct(SqlSession session){
List<Product> products = session.selectList("listAllProduct");
System.out.println("查询所有的");
for (Product p :
products) {
System.out.println(p);
}
}
/**
* 模糊查找
* @param session
*/
public static void listProductByName(SqlSession session){
Map<String,Object> map = new HashMap<>();
map.put("name","a");
map.put("price",80);
List<Product> products = session.selectList("listAllProduct",map);
System.out.println("模糊查找");
for (Product p :
products) {
System.out.println(p);
}
}
/**
* 更新商品
* @param session
*/
public static void updateProduct(SqlSession session){
Product product = session.selectOne("getProduct",3);
//System.out.println(product);
product.setName("product d");
product.setPrice((float) 99.99);
//System.out.println(product);
session.update("updateProduct",product);
}
/**
* 添加一个Category
* @param mapper
*/
private static void addCategory(CategoryMapper mapper){
Category category = new Category();
category.setName("新增的Category");
mapper.add(category);
listCategory(mapper);
}
/**
* 删除一个Category
* @param mapper
*/
private static void deleteCategory(CategoryMapper mapper){
mapper.delete(4);
listCategory(mapper);
}
/**
* 修改category
* @param mapper
*/
private static void updateCategory(CategoryMapper mapper){
Category category = mapper.get(3);
category.setName("修改过的Category");
mapper.update(category);
listCategory(mapper);
}
/**
* 显示所有的Category
* @param mapper
*/
private static void listCategory(CategoryMapper mapper){
List<Category> categoryList = mapper.list();
for (Category c :
categoryList) {
System.out.println(c.getId()+"\t"+c.getName());
}
}
}
测试结果:
![v2-2dac773f621c41f34df096269205496e_b.jpg](https://i-blog.csdnimg.cn/blog_migrate/e837bb66b23bfeb0973e3ca77be9422c.png)