MyBatis注解
XML配置方式:
优:容易编辑,配置比较集中,方便修改,在大业务量的系统里面,通过xml配置会方便后人理解整个系统的架构,修改之后直接重启应用即可
注解方式:
优:方便,简洁,配置信息和 Java 代码放在一起,有助于增强程序的内聚性。
缺:分散到各个class文件中,所以不宜维护, 修改之后你需要重新打包,发布,重启应用。
CRUD注解
本例把MyBatis框架入门(一)XML方式的CRUD修改为注解方式
删除Category.xml,创建CategoryMapper接口
package 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 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="mapper.CategoryMapper"/>
在主类编写运行逻辑
public class App {
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);
add(mapper);
delete(mapper);
get(mapper);
update(mapper);
listAll(mapper);
session.commit();
session.close();
}
private static void update(CategoryMapper mapper) {
Category c= mapper.get(8);
c.setName("修改了的Category名稱");
mapper.update(c);
listAll(mapper);
}
private static void get(CategoryMapper mapper) {
Category c= mapper.get(8);
System.out.println(c.getName());
}
private static void delete(CategoryMapper mapper) {
mapper.delete(2);
listAll(mapper);
}
private static void add(CategoryMapper mapper) {
Category c = new Category();
c.setName("新增加的Category");
mapper.add(c);
listAll(mapper);
}
private static void listAll(CategoryMapper mapper) {
List<Category> cs = mapper.list();
for (Category c : cs) {
System.out.println(c.getName());
}
}
}
一对多注解
本例把MyBatis框架进阶(二)XML方式的一对多修改为注解方式
修改CategoryMapper接口
@Select注解获取Category类本身
@Results 通过@Result和@Many中调用ProductMapper.listByCategory()方法相结合,来获取一对多关系
package 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 pojo.Category;
public interface CategoryMapper {
@Select(" select * from category ")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "products", javaType = List.class, column = "id", many = @Many(select = "mapper.ProductMapper.listByCategory") )
})
public List<Category> list();
}
创建ProductMapper接口
注解@Select用于根据分类id获取产品集合
package mapper;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import pojo.Product;
public interface ProductMapper {
@Select(" select * from product where cid = #{cid}")
public List<Product> listByCategory(int cid);
}
修改mybatis-config.xml配置文件
添加ProductMapper映射
<mapper class="mapper.ProductMapper"/>
在主类中编写运行逻辑
public class App {
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);
listAll(mapper);
session.commit();
session.close();
}
private static void listAll(CategoryMapper mapper) {
List<Category> cs = mapper.list();
for (Category c : cs) {
System.out.println(c.getName());
List<Product> ps = c.getProducts();
for (Product p : ps) {
System.out.println("\t"+p.getName());
}
}
}
}
多对一注解
本例把MyBatis框架进阶(二)XML方式的多对一修改为注解方式
修改CategoryMapper接口
package mapper;
import org.apache.ibatis.annotations.Select;
import pojo.Category;
public interface CategoryMapper {
@Select(" select * from category where id = #{id}")
public Category get(int id);
}
修改ProductMapper接口
package 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 pojo.Product;
public interface ProductMapper {
@Select(" select * from product ")
@Results({
@Result(property="category",column="cid",one=@One(select="mapper.CategoryMapper.get"))
})
public List<Product> list();
}
在主类中编写运行逻辑
public class App {
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();
ProductMapper mapper = session.getMapper(ProductMapper.class);
List<Product> ps= mapper.list();
for (Product p : ps) {
System.out.println(p + "\t对应的分类是:\t" + p.getCategory().getName());
}
session.commit();
session.close();
}
}
多对多注解
本例把MyBatis框架进阶(二)XML方式的多对多修改为注解方式
修改ProductMapper接口
package mapper;
import org.apache.ibatis.annotations.Select;
import pojo.Product;
public interface ProductMapper {
@Select("select * from product where id = #{id}")
public Product get(int id);
}
创建OrderItemMapper接口
新增OrderItemMapper,提供listByOrder方法。这里会与Product建立多对一关
package 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 pojo.OrderItem;
public interface OrderItemMapper {
@Select(" select * from order_item where oid = #{oid}")
@Results({
@Result(property="product",column="pid",one=@One(select="com.how2java.mapper.ProductMapper.get"))
})
public List<OrderItem> listByOrder(int oid);
}
创建OrdersMapper接口
新增OrderMapper,提供list方法,这里会与OrderItem建立一对多关系
package 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 pojo.Order;
public interface OrdersMapper {
@Select("select * from orders")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "orderItems", javaType = List.class, column = "id",
many = @Many(select = "mapper.OrderItemMapper.listByOrder"))
})
public List<Order> list();
}
修改mybatis-config.xml配置文件
添加OrdersMapper和OrderItemMapper映射
<mapper class="mapper.OrderItemMapper"/>
<mapper class="mapper.OrderMapper"/>
在主类中编写运行逻辑
运行测试遍历所有的订单,再通过一对多和多对一,间接地多对多遍历出产品。
public class App {
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();
listOrders(session);
session.commit();
session.close();
}
private static void listOrders(SqlSession session) {
OrdersMapper mapper =session.getMapper(OrdersMapper.class);
List<Orders> os = mapper.list();
for (Orders o : os) {
System.out.println(o.getCode());
List<OrderItem> ois= o.getOrderItems();
if(null!=ois){
for (OrderItem oi : ois) {
System.out.format("\t%s\t%f\t%d%n", oi.getProduct().getName(),oi.getProduct().getPrice(),oi.getNumber());
}
}
}
}
}
动态SQL注解
创建CategoryDynaSqlProvider
新增CategoryDynaSqlProvider,提供CRUD对应的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();
}
}
修改CategoryMapper接口
public interface CategoryMapper {
@InsertProvider(type=CategoryDynaSqlProvider.class,method="add")
public int add(Category category);
@DeleteProvider(type=CategoryDynaSqlProvider.class,method="delete")
public void delete(int id);
@SelectProvider(type=CategoryDynaSqlProvider.class,method="get")
public Category get(int id);
@UpdateProvider(type=CategoryDynaSqlProvider.class,method="update")
public int update(Category category);
@SelectProvider(type=CategoryDynaSqlProvider.class,method="list")
public List<Category> list();
}
在主类中编写运行逻辑
public class App {
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);
add(mapper);
delete(mapper);
get(mapper);
update(mapper);
listAll(mapper);
session.commit();
session.close();
}
private static void update(CategoryMapper mapper) {
Category c= mapper.get(14);
c.setName("修改了的Category名稱");
mapper.update(c);
listAll(mapper);
}
private static void get(CategoryMapper mapper) {
Category c= mapper.get(14);
System.out.println(c.getName());
}
private static void delete(CategoryMapper mapper) {
mapper.delete(13);
listAll(mapper);
}
private static void add(CategoryMapper mapper) {
Category c = new Category();
c.setName("新增加的Category");
mapper.add(c);
listAll(mapper);
}
private static void listAll(CategoryMapper mapper) {
List<Category> cs = mapper.list();
for (Category c : cs) {
System.out.println(c.getName());
}
}
}