spring-data-jpa ----OneToMany 一對多

環(huán)境搭建

導(dǎo)入依賴? maven3.6.3

<properties>

? ? ? ? <spring.version>5.2.5.RELEASE</spring.version>

? ? ? ? <hibernate.version>5.4.10.Final</hibernate.version>

? ? ? ? <slf4j.version>1.7.30</slf4j.version>

? ? ? ? <log4j.version>2.12.1</log4j.version>

? ? ? ? <druid.version>1.1.21</druid.version>

? ? ? ? <mysql.version>5.1.6</mysql.version>

? ? </properties>

? ? <dependencies>

? ? ? ? <!-- spring beg -->

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.springframework</groupId>

? ? ? ? ? ? <artifactId>spring-aop</artifactId>

? ? ? ? ? ? <version>${spring.version}</version>

? ? ? ? </dependency>

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.aspectj</groupId>

? ? ? ? ? ? <artifactId>aspectjweaver</artifactId>

? ? ? ? ? ? <version>1.9.5</version>

? ? ? ? </dependency>

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.springframework</groupId>

? ? ? ? ? ? <artifactId>spring-context</artifactId>

? ? ? ? ? ? <version>${spring.version}</version>

? ? ? ? </dependency>

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.springframework</groupId>

? ? ? ? ? ? <artifactId>spring-context-support</artifactId>

? ? ? ? ? ? <version>${spring.version}</version>

? ? ? ? </dependency>

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.springframework</groupId>

? ? ? ? ? ? <artifactId>spring-test</artifactId>

? ? ? ? ? ? <version>${spring.version}</version>

? ? ? ? </dependency>

? ? ? ? <!-- spring對orm框架的支持包-->

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.springframework</groupId>

? ? ? ? ? ? <artifactId>spring-orm</artifactId>

? ? ? ? ? ? <version>${spring.version}</version>

? ? ? ? </dependency>

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.springframework</groupId>

? ? ? ? ? ? <artifactId>spring-beans</artifactId>

? ? ? ? ? ? <version>${spring.version}</version>

? ? ? ? </dependency>

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.springframework</groupId>

? ? ? ? ? ? <artifactId>spring-core</artifactId>

? ? ? ? ? ? <version>${spring.version}</version>

? ? ? ? </dependency>

? ? ? ? <!-- hibernate beg -->

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.hibernate</groupId>

? ? ? ? ? ? <artifactId>hibernate-entitymanager</artifactId>

? ? ? ? ? ? <version>${hibernate.version}</version>

? ? ? ? </dependency>

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.hibernate</groupId>

? ? ? ? ? ? <artifactId>hibernate-core</artifactId>

? ? ? ? ? ? <version>${hibernate.version}</version>

? ? ? ? </dependency>

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.hibernate.validator</groupId>

? ? ? ? ? ? <artifactId>hibernate-validator</artifactId>

? ? ? ? ? ? <version>6.1.2.Final</version>

? ? ? ? ? ? <exclusions>

? ? ? ? ? ? ? ? <exclusion>

? ? ? ? ? ? ? ? ? ? <artifactId>classmate</artifactId>

? ? ? ? ? ? ? ? ? ? <groupId>com.fasterxml</groupId>

? ? ? ? ? ? ? ? </exclusion>

? ? ? ? ? ? </exclusions>

? ? ? ? </dependency>

? ? ? ? <!-- hibernate end -->

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>mysql</groupId>

? ? ? ? ? ? <artifactId>mysql-connector-java</artifactId>

? ? ? ? ? ? <version>${mysql.version}</version>

? ? ? ? </dependency>

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>com.alibaba</groupId>

? ? ? ? ? ? <artifactId>druid</artifactId>

? ? ? ? ? ? <version>${druid.version}</version>

? ? ? ? </dependency>

? ? ? ? <!-- spring data jpa 的坐標(biāo) -->

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.springframework.data</groupId>

? ? ? ? ? ? <artifactId>spring-data-jpa</artifactId>

? ? ? ? ? ? <version>2.2.6.RELEASE</version>

? ? ? ? ? ? <exclusions>

? ? ? ? ? ? ? ? <exclusion>

? ? ? ? ? ? ? ? ? ? <artifactId>slf4j-api</artifactId>

? ? ? ? ? ? ? ? ? ? <groupId>org.slf4j</groupId>

? ? ? ? ? ? ? ? </exclusion>

? ? ? ? ? ? </exclusions>

? ? ? ? </dependency>

? ? ? ? <!--? el beg 使用spring data jpa 必須引入 -->

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>javax.el</groupId>

? ? ? ? ? ? <artifactId>javax.el-api</artifactId>

? ? ? ? ? ? <version>3.0.0</version>

? ? ? ? </dependency>

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.glassfish</groupId>

? ? ? ? ? ? <artifactId>javax.el</artifactId>

? ? ? ? ? ? <version>3.0.0</version>

? ? ? ? </dependency>

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.slf4j</groupId>

? ? ? ? ? ? <artifactId>slf4j-api</artifactId>

? ? ? ? ? ? <version>${slf4j.version}</version>

? ? ? ? </dependency>

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>org.apache.logging.log4j</groupId>

? ? ? ? ? ? <artifactId>log4j-api</artifactId>

? ? ? ? ? ? <version>${log4j.version}</version>

? ? ? ? </dependency>

? ? ? ? <dependency>

? ? ? ? ? ? <groupId>junit</groupId>

? ? ? ? ? ? <artifactId>junit</artifactId>

? ? ? ? ? ? <version>4.12</version>

? ? ? ? </dependency>

? ? </dependencies>

編寫配置文件

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"? ? ? xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"? ? ? xmlns:context="http://www.springframework.org/schema/context"? ? ? xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"? ? ? xmlns:jpa="http://www.springframework.org/schema/data/jpa"? ? ? xmlns:task="http://www.springframework.org/schema/task"? ? ? xmlns:contxt="http://www.springframework.org/schema/context"? ? ? xsi:schemaLocation="

? ? ? ? http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

? ? ? ? http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd

? ? ? ? http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

? ? ? ? http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd

? ? ? ? http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd

? ? ? ? http://www.springframework.org/schema/data/jpa

? ? ? ? http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"><!-- 配置實(shí)體類管理工廠 --><bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"><property name="dataSource" ref="dataSource"/><property name="packagesToScan" value="com.ytfs.entity"/><property name="persistenceProvider"><bean class="org.hibernate.jpa.HibernatePersistenceProvider"/></property><property name="jpaVendorAdapter"><bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"><property name="showSql" value="true"/><property name="database" value="MYSQL"/><property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/><property name="generateDdl" value="false"/></bean></property></bean><!-- 配置事務(wù)管理器 --><bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!-- 整合jpa --><jpa:repositories base-package="com.ytfs.dao" transaction-manager-ref="transactionManager"? ? ? ? ? ? ? ? ? ? ? entity-manager-factory-ref="entityManagerFactoryBean"/><!-- spring的包掃描 --><context:component-scan base-package="com.ytfs"/><!-- 整合數(shù)據(jù)源 --><context:property-placeholder location="classpath:jdbcConfig.properties"/><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${jdbc.driver}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/><property name="url" value="${jdbc.url}"/></bean></beans>

實(shí)體類編寫


注解說明

@OneToMany:

? ? ? 作用:建立一對多的關(guān)系映射

? ? 屬性:

? ? ? ? targetEntityClass:指定多的多方的類的字節(jié)碼

? ? ? ? mappedBy:指定從表實(shí)體類中引用主表對象的名稱。

? ? ? ? cascade:指定要使用的級聯(lián)操作

? ? ? ? fetch:指定是否采用延遲加載

? ? ? ? orphanRemoval:是否使用孤兒刪除

@ManyToOne

? ? 作用:建立多對一的關(guān)系

? ? 屬性:

? ? ? ? targetEntityClass:指定一的一方實(shí)體類字節(jié)碼

? ? ? ? cascade:指定要使用的級聯(lián)操作

? ? ? ? fetch:指定是否采用延遲加載

? ? ? ? optional:關(guān)聯(lián)是否可選蔼水。如果設(shè)置為false帜消,則必須始終存在非空關(guān)系。

@JoinColumn

? ? 作用:用于定義主鍵字段和外鍵字段的對應(yīng)關(guān)系伶跷。

? ? 屬性:

? ? ? ? name:指定外鍵字段的名稱

? ? ? ? referencedColumnName:指定引用主表的主鍵字段名稱

? ? ? ? unique:是否唯一栅盲。默認(rèn)值不唯一

? ? ? ? nullable:是否允許為空。默認(rèn)值允許讼稚。

? ? ? ? insertable:是否允許插入谅年。默認(rèn)值允許茧痒。

? ? ? ? updatable:是否允許更新。默認(rèn)值允許融蹂。

? ? ? ? columnDefinition:列的定義信息旺订。


Customer

package xyz.ytfs.entity;import org.springframework.test.context.ContextConfiguration;importjavax.persistence.*;import java.util.HashSet;import java.util.Set;/** * @Classname Customer

* @Description TODO(客戶的實(shí)體類)

* @Date 2020/5/8 23:20

* @Created by ytfs

*/@Entity

@Table(name = "cst_customer")publicclass Customer {

? ? /**? ? * CREATE TABLE `cst_linkman` (

? ? * `lkm_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '聯(lián)系人編號(主鍵)',

? ? * `lkm_name` varchar(16) DEFAULT NULL COMMENT '聯(lián)系人姓名',

? ? * `lkm_gender` char(1) DEFAULT NULL COMMENT '聯(lián)系人性別',

? ? * `lkm_phone` varchar(16) DEFAULT NULL COMMENT '聯(lián)系人辦公電話',

? ? * `lkm_mobile` varchar(16) DEFAULT NULL COMMENT '聯(lián)系人手機(jī)',

? ? * `lkm_email` varchar(64) DEFAULT NULL COMMENT '聯(lián)系人郵箱',

? ? * `lkm_position` varchar(16) DEFAULT NULL COMMENT '聯(lián)系人職位',

? ? * `lkm_memo` varchar(512) DEFAULT NULL COMMENT '聯(lián)系人備注',

? ? * `lkm_cust_id` bigint(32) NOT NULL COMMENT '客戶id(外鍵)',

? ? * PRIMARY KEY (`lkm_id`),

? ? * KEY `FK_cst_linkman_lkm_cust_id` (`lkm_cust_id`),

? ? * CONSTRAINT `FK_cst_linkman_lkm_cust_id` FOREIGN KEY (`lkm_cust_id`) REFERENCES `cst_customer` (`cust_id`) ON DELETE NO ACTION ON UPDATE NO ACTION

? ? * ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

? ? */? ? @Id

? ? @GeneratedValue(strategy = GenerationType.IDENTITY)

? ? @Column(name = "cust_id")

? ? private Long custId;

? ? @Column(name = "cust_name")

? ? private String custName;

? ? @Column(name = "cust_source")

? ? private String custSource;

? ? @Column(name = "cust_industry")

? ? private String custIndustry;

? ? @Column(name = "cust_level")

? ? private String custLevel;

? ? @Column(name = "cust_address")

? ? private String custAddress;

? ? @Column(name = "cust_phone")

? ? private String custPhone;

? ? /*? ? 表達(dá)一對多的關(guān)系

? ? *//**? ? *? * 使用注解的形式配置多表關(guān)系

? ? *? ? ? ? ? ? 1.聲明關(guān)系

? ? *? ? ? ? ? ? ? ? @OneToMany : 配置一對多關(guān)系

? ? *? ? ? ? ? ? ? ? ? ? targetEntity :對方對象的字節(jié)碼對象

? ? *? ? ? ? ? ? 2.配置外鍵(中間表)

? ? *? ? ? ? ? ? ? ? ? ? @JoinColumn : 配置外鍵

? ? *? ? ? ? ? ? ? ? ? ? ? ? name:外鍵字段名稱

? ? *? ? ? ? ? ? ? ? ? ? ? ? referencedColumnName:參照的主表的主鍵字段名稱

? ? *

? ? *? ? ? ? *在客戶實(shí)體類上(一的一方)添加了外鍵了配置,所以對于客戶而言超燃,也具備了維護(hù)外鍵的作用

? ? *///@OneToMany(targetEntity = LinkMan.class)

? ? //@JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")/**? ? * 放棄外鍵維護(hù)權(quán)

? ? * mappedBy:對方配置關(guān)系的屬性名稱\? 這里就是值得LinkMan中Customer對象得變量名稱

? ? * cascade : 配置級聯(lián)(可以配置到設(shè)置多表的映射關(guān)系的注解上)

? ? * CascadeType.all? ? ? ? : 所有

? ? * MERGE? ? ? :更新

? ? * PERSIST? ? :保存

? ? * REMOVE? ? ? :刪除

? ? * <p>

? ? * fetch : 配置關(guān)聯(lián)對象的加載方式

? ? * EAGER? :立即加載

? ? * LAZY? ? :延遲加載

? ? */? ? @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)

? ? privateSet linkMans =newHashSet<>();

? ? public Long getCustId() {

? ? ? ? return custId;

? ? }

? ? publicvoid setCustId(Long custId) {

? ? ? ? this.custId = custId;

? ? }

? ? public String getCustName() {

? ? ? ? return custName;

? ? }

? ? publicvoid setCustName(String custName) {

? ? ? ? this.custName = custName;

? ? }

? ? public String getCustSource() {

? ? ? ? return custSource;

? ? }

? ? publicvoid setCustSource(String custSource) {

? ? ? ? this.custSource = custSource;

? ? }

? ? public String getCustIndustry() {

? ? ? ? return custIndustry;

? ? }

? ? publicvoid setCustIndustry(String custIndustry) {

? ? ? ? this.custIndustry = custIndustry;

? ? }

? ? public String getCustLevel() {

? ? ? ? return custLevel;

? ? }

? ? publicvoid setCustLevel(String custLevel) {

? ? ? ? this.custLevel = custLevel;

? ? }

? ? public String getCustAddress() {

? ? ? ? return custAddress;

? ? }

? ? publicvoid setCustAddress(String custAddress) {

? ? ? ? this.custAddress = custAddress;

? ? }

? ? public String getCustPhone() {

? ? ? ? return custPhone;

? ? }

? ? publicvoid setCustPhone(String custPhone) {

? ? ? ? this.custPhone = custPhone;

? ? }

? ? publicSet getLinkMans() {

? ? ? ? return linkMans;

? ? }

? ? publicvoidsetLinkMans(Set linkMans) {

? ? ? ? this.linkMans = linkMans;

? ? }

? ? @Override

? ? public String toString() {

? ? ? ? return"Customer{" +? ? ? ? ? ? ? ? "custId=" + custId +? ? ? ? ? ? ? ? ", custName='" + custName + '\'' +? ? ? ? ? ? ? ? ", custSource='" + custSource + '\'' +? ? ? ? ? ? ? ? ", custIndustry='" + custIndustry + '\'' +? ? ? ? ? ? ? ? ", custLevel='" + custLevel + '\'' +? ? ? ? ? ? ? ? ", custAddress='" + custAddress + '\'' +? ? ? ? ? ? ? ? ", custPhone='" + custPhone + '\'' +? ? ? ? ? ? ? ? '}';

? ? }

}

LinkMan

package xyz.ytfs.entity;importjavax.persistence.*;/** * @Classname LinkMan

* @Description TODO(聯(lián)系人的實(shí)體類)

* @Date 2020/5/8 23:16

* @Created by ytfs

*/@Entity

@Table(name = "cst_linkman")publicclass LinkMan {

? ? /**? ? * CREATE TABLE `cst_customer` (

? ? *? `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客戶編號(主鍵)',

? ? *? `cust_name` varchar(32) NOT NULL COMMENT '客戶名稱(公司名稱)',

? ? *? `cust_source` varchar(32) DEFAULT NULL COMMENT '客戶信息來源',

? ? *? `cust_industry` varchar(32) DEFAULT NULL COMMENT '客戶所屬行業(yè)',

? ? *? `cust_level` varchar(32) DEFAULT NULL COMMENT '客戶級別',

? ? *? `cust_address` varchar(128) DEFAULT NULL COMMENT '客戶聯(lián)系地址',

? ? *? `cust_phone` varchar(64) DEFAULT NULL COMMENT '客戶聯(lián)系電話',

? ? *? PRIMARY KEY (`cust_id`)

? ? * ) ENGINE=InnoDB AUTO_INCREMENT=94 DEFAULT CHARSET=utf8;

? ? */? ? @Id

? ? @GeneratedValue(strategy = GenerationType.IDENTITY)

? ? @Column(name = "lkm_id")

? ? private Long lkmId;

? ? @Column(name = "lkm_name")

? ? private String lkmName;

? ? @Column(name = "lkm_gender")

? ? private String lkmGender;

? ? @Column(name = "lkm_phone")

? ? private String lkmPhone;

? ? @Column(name = "lkm_mobile")

? ? private String lkmMobile;

? ? @Column(name = "lkm_email")

? ? private String lkmEmail;

? ? @Column(name = "lkm_position")

? ? private String lkmPosition;

? ? @Column(name = "lkm_memo")

? ? private String lkmMemo;

? ? /*? ? 表達(dá)多對一的關(guān)系

? ? */? ? @ManyToOne(targetEntity = Customer.class)

? ? @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")

? ? private Customer customer;

? ? public Long getLkmId() {

? ? ? ? return lkmId;

? ? }

? ? publicvoid setLkmId(Long lkmId) {

? ? ? ? this.lkmId = lkmId;

? ? }

? ? public String getLkmName() {

? ? ? ? return lkmName;

? ? }

? ? publicvoid setLkmName(String lkmName) {

? ? ? ? this.lkmName = lkmName;

? ? }

? ? public String getLkmGender() {

? ? ? ? return lkmGender;

? ? }

? ? publicvoid setLkmGender(String lkmGender) {

? ? ? ? this.lkmGender = lkmGender;

? ? }

? ? public String getLkmPhone() {

? ? ? ? return lkmPhone;

? ? }

? ? publicvoid setLkmPhone(String lkmPhone) {

? ? ? ? this.lkmPhone = lkmPhone;

? ? }

? ? public String getLkmMobile() {

? ? ? ? return lkmMobile;

? ? }

? ? publicvoid setLkmMobile(String lkmMobile) {

? ? ? ? this.lkmMobile = lkmMobile;

? ? }

? ? public String getLkmEmail() {

? ? ? ? return lkmEmail;

? ? }

? ? publicvoid setLkmEmail(String lkmEmail) {

? ? ? ? this.lkmEmail = lkmEmail;

? ? }

? ? public String getLkmPosition() {

? ? ? ? return lkmPosition;

? ? }

? ? publicvoid setLkmPosition(String lkmPosition) {

? ? ? ? this.lkmPosition = lkmPosition;

? ? }

? ? public String getLkmMemo() {

? ? ? ? return lkmMemo;

? ? }

? ? publicvoid setLkmMemo(String lkmMemo) {

? ? ? ? this.lkmMemo = lkmMemo;

? ? }

? ? public Customer getCustomer() {

? ? ? ? return customer;

? ? }

? ? publicvoid setCustomer(Customer customer) {

? ? ? ? this.customer = customer;

? ? }

? ? @Override

? ? public String toString() {

? ? ? ? return"LinkMan{" +? ? ? ? ? ? ? ? "lkmId=" + lkmId +? ? ? ? ? ? ? ? ", lkmName='" + lkmName + '\'' +? ? ? ? ? ? ? ? ", lkmGender='" + lkmGender + '\'' +? ? ? ? ? ? ? ? ", lkmPhone='" + lkmPhone + '\'' +? ? ? ? ? ? ? ? ", lkmMobile='" + lkmMobile + '\'' +? ? ? ? ? ? ? ? ", lkmEmail='" + lkmEmail + '\'' +? ? ? ? ? ? ? ? ", lkmPosition='" + lkmPosition + '\'' +? ? ? ? ? ? ? ? ", lkmMemo='" + lkmMemo + '\'' +? ? ? ? ? ? ? ? '}';

? ? }

}

測試類

package xyz.ytfs.test;import org.hibernate.loader.plan.build.internal.returns.CollectionFetchableIndexAnyGraph;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 xyz.ytfs.dao.ICustomerDao;import xyz.ytfs.dao.ILinkMan;import xyz.ytfs.entity.Customer;import xyz.ytfs.entity.LinkMan;import javax.transaction.Transactional;import javax.validation.constraints.AssertFalse;import java.util.List;import java.util.Optional;/** * @Classname JpaOnetoManyTest

* @Description TODO(JPA多對一的測試類)

* @Date 2020/5/9 0:10

* @Created by ytfs

*/@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations = "classpath:applicationContext.xml")publicclass JpaOnetoManyTest {

? ? @Autowired

? ? private ICustomerDao customerDao;

? ? @Autowired

? ? private ILinkMan linkManDao;

? ? @Test

? ? @Transactional? ? //配置事務(wù)@Rollback(false)//不自動回滾publicvoid testSave1() {

? ? ? ? Customer customer =new Customer();

? ? ? ? customer.setCustName("雨聽風(fēng)說");

? ? ? ? LinkMan linkMan =new LinkMan();

? ? ? ? linkMan.setLkmName("小鄧");

? ? ? ? /*? ? ? ? * 配置了客戶到聯(lián)系人的關(guān)系

? ? ? ? *? ? ? 從客戶的角度上:發(fā)送兩條insert語句区拳,發(fā)送一條更新語句更新數(shù)據(jù)庫(更新外鍵)

? ? ? ? * 由于我們配置了客戶到聯(lián)系人的關(guān)系:客戶可以對外鍵進(jìn)行維護(hù)

? ? ? ? */? ? ? ? customer.getLinkMans().add(linkMan);

? ? ? ? this.customerDao.save(customer);

? ? ? ? this.linkManDao.save(linkMan);

? ? }

? ? @Test

? ? @Transactional //配置事務(wù)@Rollback(false)//不自動回滾publicvoid testSave2() {

? ? ? ? //創(chuàng)建一個(gè)客戶,創(chuàng)建一個(gè)聯(lián)系人Customer customer =new Customer();

? ? ? ? customer.setCustName("百度");

? ? ? ? LinkMan linkMan =new LinkMan();

? ? ? ? linkMan.setLkmName("小李");

? ? ? ? /**? ? ? ? * 配置聯(lián)系人到客戶的關(guān)系(多對一)

? ? ? ? *? ? 只發(fā)送了兩條insert語句

? ? ? ? * 由于配置了聯(lián)系人到客戶的映射關(guān)系(多對一)

? ? ? ? *

? ? ? ? *

? ? ? ? */? ? ? ? linkMan.setCustomer(customer);

? ? ? ? this.customerDao.save(customer);

? ? ? ? this.linkManDao.save(linkMan);

? ? }

? ? /**? ? * 會有一條多余的update語句

? ? * * 由于一的一方可以維護(hù)外鍵:會發(fā)送update語句

? ? * * 解決此問題:只需要在一的一方放棄維護(hù)權(quán)即可

? ? */? ? @Test

? ? @Transactional //配置事務(wù)@Rollback(false)//不自動回滾publicvoid testAdd2() {

? ? ? ? //創(chuàng)建一個(gè)客戶意乓,創(chuàng)建一個(gè)聯(lián)系人Customer customer =new Customer();

? ? ? ? customer.setCustName("百度");

? ? ? ? LinkMan linkMan =new LinkMan();

? ? ? ? linkMan.setLkmName("小李");

? ? ? ? linkMan.setCustomer(customer);//由于配置了多的一方到一的一方的關(guān)聯(lián)關(guān)系(當(dāng)保存的時(shí)候樱调,就已經(jīng)對外鍵賦值)customer.getLinkMans().add(linkMan);//由于配置了一的一方到多的一方的關(guān)聯(lián)關(guān)系(發(fā)送一條update語句)this.customerDao.save(customer);

? ? ? ? this.linkManDao.save(linkMan);

? ? }

? ? /**? ? * 級聯(lián)添加:保存一個(gè)客戶的同時(shí),保存客戶的所有聯(lián)系人

? ? * 需要在操作主體(這里就是Customer)的實(shí)體類上届良,配置casacde屬性

? ? */? ? @Test

? ? @Transactional

? ? @Rollback(false)

? ? publicvoid testSaveCasacde() {

? ? ? ? Customer customer =new Customer();

? ? ? ? customer.setCustName("雨聽風(fēng)說1");

? ? ? ? LinkMan linkMan =new LinkMan();

? ? ? ? linkMan.setLkmName("小李1");

? ? ? ? /*? ? ? ? 表達(dá)關(guān)系

? ? ? ? */? ? ? ? customer.getLinkMans().add(linkMan);

? ? ? ? linkMan.setCustomer(customer);

? ? ? ? /*? ? ? ? ? ? 級聯(lián)操作得時(shí)候在保存客戶得同時(shí)會自動保存客戶對應(yīng)得聯(lián)系人笆凌,但是需要在一的一方配置級聯(lián)操作

? ? ? ? */this.customerDao.save(customer);

? ? }

? ? @Test

? ? @Transactional //配置事務(wù)@Rollback(false)//不自動回滾publicvoid testCascadeRemove() {

? ? ? ? //1.查詢1號客戶Customer customer =? customerDao.getOne(1l);

? ? ? ? //2.刪除1號客戶? ? ? ? System.out.println(customer);

? ? ? ? customerDao.delete(customer);

? ? }

}

?對象導(dǎo)航查詢測試

package xyz.ytfs.test;import org.aspectj.weaver.ast.Var;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.transaction.annotation.Transactional;import xyz.ytfs.dao.ICustomerDao;import xyz.ytfs.dao.ILinkMan;import xyz.ytfs.entity.Customer;import xyz.ytfs.entity.LinkMan;import java.util.Optional;import java.util.Set;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations = "classpath:applicationContext.xml")publicclass ObjectQueryTest {

? ? @Autowired

? ? private ICustomerDao customerDao;

? ? @Autowired

? ? private ILinkMan linkManDao;

? ? //could not initialize proxy - no Session

? ? //測試對象導(dǎo)航查詢(查詢一個(gè)對象的時(shí)候,通過此對象查詢所有的關(guān)聯(lián)對象)? ? @Test

? ? @Transactional // 解決在java代碼中的no session問題publicvoid? testQuery1() {

? ? ? ? //查詢id為1的客戶Customer customer =this.customerDao.getOne(1L);

? ? ? ? //對象導(dǎo)航查詢士葫,此客戶下的所有聯(lián)系人Set linkMans = customer.getLinkMans();

? ? ? ? linkMans.forEach(System.out::println);

? ? }

? ? /**? ? * 對象導(dǎo)航查詢:

? ? *? ? ? 默認(rèn)使用的是延遲加載的形式查詢的

? ? *? ? ? ? ? 調(diào)用get方法并不會立即發(fā)送查詢乞而,而是在使用關(guān)聯(lián)對象的時(shí)候才會差和訊

? ? *? ? ? 延遲加載!

? ? * 修改配置慢显,將延遲加載改為立即加載

? ? *? ? ? fetch爪模,需要配置到多表映射關(guān)系的注解上

? ? *

? ? */? ? @Test

? ? @Transactional // 解決在java代碼中的no session問題publicvoid? testQuery2() {

? ? ? ? //查詢id為1的客戶Customer customer =this.customerDao.getOne(1L);

? ? ? ? //對象導(dǎo)航查詢,此客戶下的所有聯(lián)系人Set linkMans = customer.getLinkMans();

? ? ? ? linkMans.forEach(System.out::println);

? ? }

? ? /**? ? * 從聯(lián)系人對象導(dǎo)航查詢他的所屬客戶

? ? *? ? ? * 默認(rèn) : 立即加載

? ? *? 延遲加載:

? ? *

? ? */? ? @Test

? ? @Transactional // 解決在java代碼中的no session問題publicvoid? testQuery3() {

? ? ? ? //對象導(dǎo)航查詢所屬的客戶LinkMan linkMan =this.linkManDao.getOne(1L);

? ? ? ? Customer customer = linkMan.getCustomer();

? ? ? ? System.out.println("customer = " + customer);

? ? }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末荚藻,一起剝皮案震驚了整個(gè)濱河市屋灌,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌应狱,老刑警劉巖共郭,帶你破解...
    沈念sama閱讀 222,378評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異侦香,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)纽疟,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,970評論 3 399
  • 文/潘曉璐 我一進(jìn)店門罐韩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人污朽,你說我怎么就攤上這事散吵。” “怎么了?”我有些...
    開封第一講書人閱讀 168,983評論 0 362
  • 文/不壞的土叔 我叫張陵矾睦,是天一觀的道長晦款。 經(jīng)常有香客問我,道長枚冗,這世上最難降的妖魔是什么缓溅? 我笑而不...
    開封第一講書人閱讀 59,938評論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮赁温,結(jié)果婚禮上坛怪,老公的妹妹穿的比我還像新娘。我一直安慰自己股囊,他們只是感情好袜匿,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,955評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著稚疹,像睡著了一般居灯。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上内狗,一...
    開封第一講書人閱讀 52,549評論 1 312
  • 那天怪嫌,我揣著相機(jī)與錄音,去河邊找鬼其屏。 笑死喇勋,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的偎行。 我是一名探鬼主播川背,決...
    沈念sama閱讀 41,063評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼蛤袒!你這毒婦竟也來了熄云?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,991評論 0 277
  • 序言:老撾萬榮一對情侶失蹤妙真,失蹤者是張志新(化名)和其女友劉穎缴允,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體珍德,經(jīng)...
    沈念sama閱讀 46,522評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡练般,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,604評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了锈候。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片薄料。...
    茶點(diǎn)故事閱讀 40,742評論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖泵琳,靈堂內(nèi)的尸體忽然破棺而出摄职,到底是詐尸還是另有隱情誊役,我是刑警寧澤,帶...
    沈念sama閱讀 36,413評論 5 351
  • 正文 年R本政府宣布谷市,位于F島的核電站蛔垢,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏迫悠。R本人自食惡果不足惜鹏漆,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,094評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望及皂。 院中可真熱鬧甫男,春花似錦、人聲如沸验烧。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,572評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽碍拆。三九已至若治,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間感混,已是汗流浹背端幼。 一陣腳步聲響...
    開封第一講書人閱讀 33,671評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留弧满,地道東北人婆跑。 一個(gè)月前我還...
    沈念sama閱讀 49,159評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像庭呜,于是被迫代替她去往敵國和親滑进。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,747評論 2 361