MyBatis注解之一对多

MyBatis注解之一对多

准备Mapper

  • CategoryMapper接口中追加listOneToMany方法:
    @Select(" select * from category_ ")
    @Results({ 
                @Result(property = "id", column = "id"),
                @Result(property = "products", javaType = List.class, column = "id", many = @Many(select = "com.nyf.mappers.ProductMapper.listByCategory") )
            })
    public List<Category> listOneToMany();  
点击查看完整CategoryMapper

package com.nyf.mappers;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Many;

import com.nyf.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 list(); 
    
    @Select(" select * from category_ ")
    @Results({ 
                @Result(property = "id", column = "id"),
                @Result(property = "products", javaType = List.class, column = "id", many = @Many(select = "com.nyf.mappers.ProductMapper.listByCategory") )
            })
    public List listOneToMany();  
}

  • 新建ProductMapper接口,添加listByCategory方法:
    @Select(" select * from product_ where cid = #{cid}")
    public List<Product> listByCategory(int cid);
点击查看完整ProductMapper

package com.nyf.mappers;
  
import java.util.List;
 
import org.apache.ibatis.annotations.Select;
 
import com.nyf.pojo.Product;
  
public interface ProductMapper {
  
    @Select(" select * from product_ where cid = #{cid}")
    public List listByCategory(int cid);
     
}

修改配置文件

mybatis-config.xml中添加ProductMapper的映射:

<mapper class="com.nyf.mappers.ProductMapper"/> 
点击查看完整mybatis-config.xml

<?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>
   
   
   <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
        </plugin>
    </plugins>
    <!-- environments配置要连接的数据库 -->
    <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/nyf?characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    
    <!-- mappers,指明实体类对应的配置文件 -->
    <mappers>
        <mapper class="com.nyf.mappers.CategoryMapper"/> 
        <mapper class="com.nyf.mappers.ProductMapper"/>
        <mapper class="com.nyf.mappers.OrderItemMapper"/>
        <mapper class="com.nyf.mappers.OrderMapper"/> 
    </mappers>
</configuration>

编写测试类OneToMany

点击查看完整OneToMany

package com.nyf.tests;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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 com.nyf.mappers.CategoryMapper;
import com.nyf.pojo.Category;
import com.nyf.pojo.Product;

public class OneToMany {
	public static void main(String[] args) throws IOException {
		String resource = "com/nyf/config/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 cs = mapper.listOneToMany();
        for (Category c : cs) {
            System.out.println(c.getName());
            List ps = c.getProducts();
            for (Product p : ps) {
                System.out.println("\t"+p.getName());
            }
        }
    }
}

结果验证

正确结果应该如下所示:

category1
	product a
	product b
	product c
category
	product x
	product y
	product zzzzzz
上一篇:Mybatis的简介


下一篇:精尽 MyBatis 源码分析 - 基础支持层