个人觉得这个功能其实可以不用的,完全可以用连接操作,自己的逻辑清晰就好了 ###1.创建实体类
public class Ticket { private Integer ticketId; private String ticketAddress; private Integer ticketPrice; private Integer ticketCId; private Customer customer;//使用一个customer来表示顾客 ....public class Customer { private Integer customerId; private String customerName; private Integer customerTel; private Listtickets;//使用一个List来表示车票 ....
###2.编写xml文件
###3.编写总的xml文件 ``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> <!-- 设置别名 --> <typeAliases> <typeAlias alias="Customer" type="com.mucfc.model.Customer"/> <typeAlias alias="Ticket" type="com.mucfc.model.Ticket" /> </typeAliases>
</configuration> ``` ###4.编写测试类 ```java package com.hsm;
import java.io.Reader; 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.mucfc.model.Customer; import com.mucfc.model.Ticket;
public class Test { private static SqlSessionFactory sqlSessionFactory; private static Reader reader; static { try { reader = Resources.getResourceAsReader("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (Exception e) { e.printStackTrace(); } }
/* * 一对一关联查询 */public static void selectTicketById(int id) { SqlSession session = null; try { session = sqlSessionFactory.openSession(); Ticket ticket = (Ticket) session.selectOne( "com.mucfc.model.TicketMapper.selectTicketById", id); if (ticket == null) System.out.println("null"); else { System.out.println(ticket); System.out.println(ticket.getCustomer()); } } finally { session.close(); }}/* * 一对多关联查询 */public static void selectCustomerByName(String string) { SqlSession session = null; try { session = sqlSessionFactory.openSession(); Customer customer = (Customer) session .selectOne( "com.mucfc.model.CustomerMapper.selectCustomerByName", string); if (customer == null) System.out.println("null"); else { System.out.println(customer); Listtickets = customer.getTickets(); for (Ticket ticket : tickets) { System.out.println(ticket); } } } finally { session.close(); }}public static void main(String[] args) { System.out.println("==============一对一查询,根据车票来查顾客==============="); selectTicketById(1); System.out.println("==============多对一查询,根据顾客来查车票==============="); selectCustomerByName("小王");}
}