欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring data jpa配置一对多,多对多关系映射

程序员文章站 2022-04-23 23:39:44
...
//配置一对多关系映射
    /**
     *     @OneToMany(targetEntity = LinkMan.class)
     *          targetEntity配置对方的字节码文件
     *     @JoinColumn(name = "lkm_cust_id",referencedColumnName = "cust_id")
     *          name配置外键名称,referencedColumnName配置外键引用主表的主键
     */
    @OneToMany(targetEntity = LinkMan.class)
    @JoinColumn(name = "lkm_cust_id",referencedColumnName = "cust_id")
    private Set<LinkMan> linkMans=new HashSet<LinkMan>();
//配置多对一关系映射
    @ManyToOne(targetEntity = Customer.class)
    @JoinColumn(name = "lkm_cust_id",referencedColumnName = "cust_id")
    private Customer customer;

编写测试类

import com.smx.dao.CustomerDao;
import com.smx.dao.LinkManDao;
import com.smx.domain.Customer;
import com.smx.domain.LinkMan;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
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 CustomerDao customerDao;
    @Autowired
    private LinkManDao linkManDao;
    @Test
    @Transactional
    @Rollback(value = false)
    //测试保存操作
    public void addTest(){
        Customer customer=new Customer();
        customer.setCustName("百度");
        LinkMan linkMan=new LinkMan();
        linkMan.setLmkName("张三");

        customer.getLinkMans().add(linkMan);
        linkManDao.save(linkMan);
        customerDao.save(customer);


    }
}

级联操作

 @OneToMany(mappedBy = "customer",cascade = {CascadeType.MERGE})

MERGE:更新
PERSIST:保存
REMOVE:删除

上一篇: mysql多实例的搭建

下一篇: nio