第一步:分别写好对应的mapper
public void insertOrde(Order order);
public void insertCustomer(Customer customer);
第二步:分别写好对应的mapper.xml
这里的客户插入之后立马获取它的主键并将他查出来
插入客户
<insert id="insertCustomer" parameterType="Customer" useGeneratedKeys="true" keyProperty="cust_id" keyColumn="cust_id">
insert into `customer` (cust_name,cust_profession,cust_phone,email) values (#{cust_name},#{cust_profession},#{cust_phone},#{email})
</insert>
插入订单 (看见没有,这里插入的订单中外键,就是我们插入的客户的id)
<insert id="insertOrde" parameterType="Order">
insert into `order` (orderName,orderNum,orderCustId) values (#{orderName},#{orderNum},#{customer.cust_id})
</insert>
第三步:开始插入
注意事务的提交
@Test
public void test6(){
SqlSession session = MyUtils.openSession();
OrderMapper mapper = session.getMapper(OrderMapper.class);
CustomerMapper mapper1 = session.getMapper(CustomerMapper.class);
Customer customer = new Customer();
customer.setCust_name("太上老君");
Order order = new Order();
order.setOrderName("支付宝订单");
order.setCustomer(customer);
mapper1.insertCustomer(customer);
System.out.println(customer);
mapper.insertOrde(order);
session.commit();
session.close();
}