springData表关系:一对多
一、编写实体类进行表关联
1、在一张表的关联属性上添加@OneToMany注解(关联属性用来记录多的一方的信息,是个集合,一般用set)
2、在另一个实体类的关联属性上添加@ManyToOne注解和 @JoinColumn(name="custid",referencedColumnName = "cust_id")注解
二、编写dao:两个dao都继承JpaRepository<实体类名,主键属性>
三、编写测试类(用法)
package cn.lijun.jpa;
import cn.lijun.jpa.dao.CustomerDao2;
import cn.lijun.jpa.dao.LinkManDao;
import cn.lijun.jpa.entity.Customer2;
import cn.lijun.jpa.entity.LinkMan;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Commit;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class OneToManyTest {
@Autowired
private CustomerDao2 customerDao2;
@Autowired
private LinkManDao linkManDao;
@Test
@Transactional
@Commit
public void addCustomer2(){
// 1每个实体类 创建dao
//2创建Customer2对象
Customer2 customer2 = new Customer2();
customer2.setCustName("张无忌");
customer2.setCustAddress("光明顶");
customer2.setCustLevel("教主");
//3创建LinkMan对象
LinkMan linkMan1 = new LinkMan();
linkMan1.setLkmName("赵敏");
linkMan1.setLkmMobile("13111111");
LinkMan linkMan2 = new LinkMan();
linkMan2.setLkmName("小昭");
linkMan2.setLkmMobile("13166661");
LinkMan linkMan3 = new LinkMan();
linkMan3.setLkmName("灭绝师太");
linkMan3.setLkmMobile("13166661111");
// 4 配置客户和联系人之间的关系
customer2.getLinkMEN().add(linkMan1);
customer2.getLinkMEN().add(linkMan2);
customer2.getLinkMEN().add(linkMan3);
linkMan1.setCustomer(customer2);
linkMan2.setCustomer(customer2);
linkMan3.setCustomer(customer2);
//5 使用dao 把数据写入数据库
customerDao2.save(customer2);
linkManDao.save(linkMan1);
linkManDao.save(linkMan2);
linkManDao.save(linkMan3);
}
}

浙公网安备 33010602011771号