表与表关联 一对一

Posted wangshichang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了表与表关联 一对一相关的知识,希望对你有一定的参考价值。

1...表与表之间的关系

一对一: A   B  两张表  A表中的每条的记录对应的B的一条记录

   :一对一关系实现方式:

         1:使用外键关联 

    :  场景:使用客户表和客户拓展表 

    :在属性上 添加一个@OneToOne代表一个对一个的关系    在属性上添加@JoinColumn? name 存储外键的字段     referencedColumnNm 对方表的字段名称 (可以省略)

         2:使用主键关联,两个表  A  B 的主键相同。

   : 使用@PrimaryKeyJoinColumn 注解不需要配置属性   ?双方都需要添加

一对多: A   B  两张表  A表中的每条的记录对应B表中多条的记录    B表中多条的记录对应A表中一条记录

   :场景:客户和联系人之间 一对多       ? 一个客户对应多个联系人

   :单方:1  添加一个属性 记录多的一方的信息  应该是一个集合 hashset    2  在属性上添加一个注解  @OneToMany      3一定是多的一方记录外键   参照一的一方的主键

   :多方:1  在属性上添加 注解   @ManyToOne   2   在属性上添加 @joinColumn 注解

多对多: A   B  两张表    A表中的每条的记录对应B表中多条的记录      B表中的每条记录对应A表中的多条记录

   :后面补充,

 

具体实现 简单例子:

1....pom.xml 配置

技术图片
  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <project xmlns="http://maven.apache.org/POM/4.0.0"
  3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5     <modelVersion>4.0.0</modelVersion>
  6 
  7     <groupId>com.wsc</groupId>
  8     <artifactId>oneToOne</artifactId>
  9     <version>1.0-SNAPSHOT</version>
 10 
 11 
 12     <properties>
 13         <spring.version>4.2.4.RELEASE</spring.version>
 14         <hibernate.version>5.0.7.Final</hibernate.version>
 15         <slf4j.version>1.6.6</slf4j.version>
 16         <log4j.version>1.2.12</log4j.version>
 17         <c3p0.version>0.9.1.2</c3p0.version>
 18         <mysql.version>5.1.6</mysql.version>
 19         <maven.compiler.source>1.8</maven.compiler.source>
 20         <maven.compiler.target>1.8</maven.compiler.target>
 21     </properties>
 22     <dependencies>
 23         <dependency>
 24             <groupId>junit</groupId>
 25             <artifactId>junit</artifactId>
 26             <version>4.12</version>
 27             <scope>test</scope>
 28         </dependency>
 29         <!--spring start-->
 30         <dependency>
 31             <groupId>org.aspectj</groupId>
 32             <artifactId>aspectjweaver</artifactId>
 33             <version>1.6.8</version>
 34         </dependency>
 35         <dependency>
 36             <groupId>org.springframework</groupId>
 37             <artifactId>spring-aop</artifactId>
 38             <version>$spring.version</version>
 39         </dependency>
 40         <dependency>
 41             <groupId>org.springframework</groupId>
 42             <artifactId>spring-context</artifactId>
 43             <version>$spring.version</version>
 44         </dependency>
 45         <dependency>
 46             <groupId>org.springframework</groupId>
 47             <artifactId>spring-context-support</artifactId>
 48             <version>$spring.version</version>
 49         </dependency>
 50         <dependency>
 51             <groupId>org.springframework</groupId>
 52             <artifactId>spring-orm</artifactId>
 53             <version>$spring.version</version>
 54         </dependency>
 55         <dependency>
 56             <groupId>org.springframework</groupId>
 57             <artifactId>spring-beans</artifactId>
 58             <version>$spring.version</version>
 59         </dependency>
 60         <dependency>
 61             <groupId>org.springframework</groupId>
 62             <artifactId>spring-core</artifactId>
 63             <version>$spring.version</version>
 64         </dependency>
 65         <!--spring end-->
 66         <!--hibernate start-->
 67         <dependency>
 68             <groupId>org.hibernate</groupId>
 69             <artifactId>hibernate-core</artifactId>
 70             <version>$hibernate.version</version>
 71         </dependency>
 72         <dependency>
 73             <groupId>org.hibernate</groupId>
 74             <artifactId>hibernate-entitymanager</artifactId>
 75             <version>$hibernate.version</version>
 76         </dependency>
 77         <dependency>
 78             <groupId>org.hibernate</groupId>
 79             <artifactId>hibernate-validator</artifactId>
 80             <version>5.2.1.Final</version>
 81         </dependency>
 82         <!--hibernate end-->
 83         <dependency>
 84             <groupId>c3p0</groupId>
 85             <artifactId>c3p0</artifactId>
 86             <version>$c3p0.version</version>
 87         </dependency>
 88         <dependency>
 89             <groupId>log4j</groupId>
 90             <artifactId>log4j</artifactId>
 91             <version>$log4j.version</version>
 92         </dependency>
 93         <dependency>
 94             <groupId>org.slf4j</groupId>
 95             <artifactId>slf4j-api</artifactId>
 96             <version>$slf4j.version</version>
 97         </dependency>
 98         <dependency>
 99             <groupId>org.slf4j</groupId>
100             <artifactId>slf4j-log4j12</artifactId>
101             <version>$slf4j.version</version>
102         </dependency>
103         <dependency>
104             <groupId>mysql</groupId>
105             <artifactId>mysql-connector-java</artifactId>
106             <version>$mysql.version</version>
107         </dependency>
108         <dependency>
109             <groupId>org.springframework.data</groupId>
110             <artifactId>spring-data-jpa</artifactId>
111             <version>1.9.0.RELEASE</version>
112         </dependency>
113         <dependency>
114             <groupId>org.springframework</groupId>
115             <artifactId>spring-test</artifactId>
116             <version>4.2.4.RELEASE</version>
117         </dependency>
118         <dependency>
119             <groupId>javax.el</groupId>
120             <artifactId>javax.el-api</artifactId>
121             <version>2.2.4</version>
122         </dependency>
123         <dependency>
124             <groupId>org.glassfish.web</groupId>
125             <artifactId>javax.el</artifactId>
126             <version>2.2.4</version>
127         </dependency>
128     </dependencies>
129 </project>
pom.xml

2...applicationContext.xml 配置

技术图片
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 4        xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
 5        xmlns:jpa="http://www.springframework.org/schema/data/jpa"
 6        xsi:schemaLocation="
 7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 8 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
 9 http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
10 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
11 http://www.springframework.org/schema/data/jpa
12 http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
13     <!--1 数据源-->
14     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
15         <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
16         <property name="user" value="root"></property>
17         <property name="password" value="wsc"></property>
18         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/shop"></property>
19     </bean>
20     <!--2 工厂类对象-->
21     <bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
22         <property name="dataSource" ref="dataSource"></property>
23         <!--实体类的扫描器-->
24         <property name="packagesToScan" value="com.wsc.core.entity"></property>
25         <!--配置供应商的适配器-->
26         <property name="jpaVendorAdapter">
27            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
28 <!--               显示SQL在console 控制台-->
29                 <property name="showSql" value="true"></property>
30                <property name="generateDdl" value="true"></property>
31                <property name="database" value="MYSQL"></property>
32            </bean>
33         </property>
34         <property name="jpaProperties">
35 <!--          create  创建 表  并  更新 每次运行 重新创建  -->
36             <!--         update  创建 表  并  更新 每次运行 在原来基础上 CRUD -->
37             <!--          none  不创建 -->
38           <props>
39                 <prop key="hibernate.hbm2ddl.auto">create</prop>
40           </props>
41         </property>
42     </bean>
43     <!--3 事物管理配置配置事物-->
44     <bean id="jpaTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
45         <property name="entityManagerFactory" ref="entityManagerFactoryBean"></property>
46     </bean>
47     <tx:advice id="txAdvice" transaction-manager="jpaTransactionManager">
48         <tx:attributes>
49             <tx:method name="save*" propagation="REQUIRED"/>
50             <tx:method name="update*" propagation="REQUIRED"/>
51             <tx:method name="delete*" propagation="REQUIRED"/>
52             <tx:method name="add*" propagation="REQUIRED"/>
53             <tx:method name="find*" read-only="true"/>
54             <tx:method name="get*" read-only="true"/>
55             <tx:method name="*" propagation="REQUIRED"/>
56         </tx:attributes>
57     </tx:advice>
58     <aop:config>
59         <aop:pointcut id="pointcut" expression="execution(* com.wsc.core.service.*.*(..))"/>
60         <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"></aop:advisor>
61     </aop:config>
62     <!--4 dao的包扫描器-->
63     <jpa:repositories base-package="com.wsc.core.dao"
64      transaction-manager-ref="jpaTransactionManager"
65      entity-manager-factory-ref="entityManagerFactoryBean">
66     </jpa:repositories>
67 </beans>
applicationContext.xml

3....实体类 entity (使用外键关联 )

 (1):City类

技术图片
 1 package com.wsc.core.entity;
 2 
 3 
 4 import javax.persistence.*;
 5 
 6 /**
 7  * @version 1.0
 8  * @ClassName City
 9  * @Description TODO
10  * @Author WSC
11  * @Date 2019/8/20 14:18
12  **/
13 @Entity //必须加 不然会报错
14 @Table(name="city") //表名
15 public class City 
16     // 配置主键自增的策略
17     @GeneratedValue(strategy = GenerationType.IDENTITY)
18     @Column(name="id")
19     @Id
20     private Long id;
21     @Column(name="cityName")
22     private String cityName;
23     // 表示一对一关联关系
24     @OneToOne(cascade = CascadeType.ALL)
25 //     外键 name 当前表中外键的字段名
26     @JoinColumn(name="cityName",insertable=false , updatable=false)
27 
28     private Flight flight;
29 
30     public Long getId() 
31         return id;
32     
33 
34     public void setId(Long id) 
35         this.id = id;
36     
37 
38     public String getCityName() 
39         return cityName;
40     
41 
42     public void setCityName(String cityName) 
43         this.cityName = cityName;
44     
45 
46     public Flight getFlight() 
47         return flight;
48     
49 
50     public void setFlight(Flight flight) 
51         this.flight = flight;
52     
53 
54     @Override
55     public String toString() 
56         return "City" +
57                 "id=" + id +
58                 ", cityName=‘" + cityName + ‘\‘‘ +
59                 ", flight=" + flight +
60                 ‘‘;
61     
62 
City

(2):Flight类

技术图片
 1 package com.wsc.core.entity;
 2 
 3 import javax.persistence.*;
 4 import java.util.Date;
 5 
 6 /**
 7  * @version 1.0
 8  * @ClassName Flight
 9  * @Description TODO
10  * @Author WSC
11  * @Date 2019/8/20 14:26
12  **/
13 @Entity
14 @Table(name="flight")
15 public class Flight 
16     @Column(name="id")
17     @Id
18     @GeneratedValue(strategy = GenerationType.IDENTITY)
19     private  Long id;
20     @Column(name="flightNo")
21     private String flightNo;
22    @Column(name="arriveDate")
23    private Date arriveDate;
24     // 表示一对一关联关系
25     @OneToOne
26     // 外键 name 当前表中外键的字段名  referencedColumnName  对方表的字段名称  (可以省略)
27     @JoinColumn(name="arriveCity",referencedColumnName = "cityName")
28 
29     private City city;
30 
31     public Long getId() 
32         return id;
33     
34 
35     public void setId(Long id) 
36         this.id = id;
37     
38 
39     public String getFlightNo() 
40         return flightNo;
41     
42 
43     public void setFlightNo(String flightNo) 
44         this.flightNo = flightNo;
45     
46 
47     public Date getArriveDate() 
48         return arriveDate;
49     
50 
51     public void setArriveDate(Date arriveDate) 
52         this.arriveDate = arriveDate;
53     
54 
55 
56     public City getCity() 
57         return city;
58     
59 
60     public void setCity(City city) 
61         this.city = city;
62     
63 
64     @Override
65     public String toString() 
66         return "Flight" +
67                 "id=" + id +
68                 ", flightNo=‘" + flightNo + ‘\‘‘ +
69                 ", arriveDate=" + arriveDate +
70                 ", city=" + city +
71                 ‘‘;
72     
73 
Flight

 3....实体类 entity (使用主键关联)

(1):City类

技术图片
 1 package com.wsc.core.entity;
 2 
 3 
 4 import javax.persistence.*;
 5 
 6 /**
 7  * @version 1.0
 8  * @ClassName City
 9  * @Description TODO
10  * @Author WSC
11  * @Date 2019/8/20 14:18
12  **/
13 @Entity //必须加 不然会报错
14 @Table(name="city") //表名
15 public class City 
16     // 配置主键自增的策略
17     @GeneratedValue(strategy = GenerationType.IDENTITY)
18     @Column(name="id")
19     @Id
20     private Long id;
21     @Column(name="cityName")
22     private String cityName;
23     // 表示一对一关联关系
24     @OneToOne(cascade = CascadeType.ALL)
25 
26     // 使用主键关联
27     @PrimaryKeyJoinColumn
28     private Flight flight;
29 
30     public Long getId() 
31         return id;
32     
33 
34     public void setId(Long id) 
35         this.id = id;
36     
37 
38     public String getCityName() 
39         return cityName;
40     
41 
42     public void setCityName(String cityName) 
43         this.cityName = cityName;
44     
45 
46     public Flight getFlight() 
47         return flight;
48     
49 
50     public void setFlight(Flight flight) 
51         this.flight = flight;
52     
53 
54     @Override
55     public String toString() 
56         return "City" +
57                 "id=" + id +
58                 ", cityName=‘" + cityName + ‘\‘‘ +
59                 ", flight=" + flight +
60                 ‘‘;
61     
62 
City

(2):Flight类

技术图片
 1 package com.wsc.core.entity;
 2 
 3 import javax.persistence.*;
 4 import java.util.Date;
 5 
 6 /**
 7  * @version 1.0
 8  * @ClassName Flight
 9  * @Description TODO
10  * @Author WSC
11  * @Date 2019/8/20 14:26
12  **/
13 @Entity
14 @Table(name="flight")
15 public class Flight 
16     @Column(name="id")
17     @Id
18     @GeneratedValue(strategy = GenerationType.IDENTITY)
19     private  Long id;
20     @Column(name="flightNo")
21     private String flightNo;
22    @Column(name="arriveDate")
23    private Date arriveDate;
24     // 表示一对一关联关系
25     @OneToOne
26 
27     // 使用主键关联
28     @PrimaryKeyJoinColumn
29     private City city;
30 
31     public Long getId() 
32         return id;
33     
34 
35     public void setId(Long id) 
36         this.id = id;
37     
38 
39     public String getFlightNo() 
40         return flightNo;
41     
42 
43     public void setFlightNo(String flightNo) 
44         this.flightNo = flightNo;
45     
46 
47     public Date getArriveDate() 
48         return arriveDate;
49     
50 
51     public void setArriveDate(Date arriveDate) 
52         this.arriveDate = arriveDate;
53     
54 
55 
56     public City getCity() 
57         return city;
58     
59 
60     public void setCity(City city) 
61         this.city = city;
62     
63 
64     @Override
65     public String toString() 
66         return "Flight" +
67                 "id=" + id +
68                 ", flightNo=‘" + flightNo + ‘\‘‘ +
69                 ", arriveDate=" + arriveDate +
70                 ", city=" + city +
71                 ‘‘;
72     
73 
Flight

4...dao类 (使用外键关联 ) (使用主键关联)

 (1)Citydao类

技术图片
1 package com.wsc.core.dao;
2 
3 import com.wsc.core.entity.City;
4 import org.springframework.data.jpa.repository.JpaRepository;
5 
6 public interface CityDao extends JpaRepository<City,Long> 
7 
CityDao

 (2)FlightDao类

技术图片
1 package com.wsc.core.dao;
2 
3 import com.wsc.core.entity.Flight;
4 import org.springframework.data.jpa.repository.JpaRepository;
5 
6 public interface FlightDao extends JpaRepository<Flight,Long> 
7 
FlightDao

5...test( 使用外键关联 )

技术图片
 1 package com.wsc.core.onetone;
 2 
 3 import com.wsc.core.dao.CityDao;
 4 import com.wsc.core.dao.FlightDao;
 5 import com.wsc.core.entity.City;
 6 import com.wsc.core.entity.Flight;
 7 import org.junit.Test;
 8 import org.junit.runner.RunWith;
 9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.test.annotation.Commit;
11 import org.springframework.test.context.ContextConfiguration;
12 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
13 import org.springframework.transaction.annotation.Transactional;
14 
15 import java.util.Date;
16 
17 /**
18  * @version 1.0
19  * @ClassName TestOneTOne
20  * @Description TODO
21  * @Author WSC
22  * @Date 2019/8/20 14:42
23  **/
24 @RunWith(SpringJUnit4ClassRunner.class)//spring框架测试
25 @ContextConfiguration(locations = "classpath:applicationContext.xml") //引入xml配置文件
26 public class TestOneTOne 
27     //自动注入
28     @Autowired
29     private CityDao cityDao;
30     @Autowired
31     private FlightDao flightDao;
32     @Test
33     //事务 必须加
34     @Transactional
35     //提价 必须加
36     @Commit
37     public void test01()
38         //city对象 存数据
39         City city = new City();
40         city.setCityName("上海");
41         //flight 对象 存数据
42         Flight flight = new Flight();
43         flight.setArriveDate(new Date());
44         flight.setFlightNo("123");
45         //配置关联关系
46         city.setFlight(flight);
47         flight.setCity(city);
48         // 保存 入 数据库
49         cityDao.save(city);
50         flightDao.save(flight);
51     
52 
test

5...test  (使用主键关联)

技术图片
 1 package com.wsc.core.onetone;
 2 
 3 import com.wsc.core.dao.CityDao;
 4 import com.wsc.core.dao.FlightDao;
 5 import com.wsc.core.entity.City;
 6 import com.wsc.core.entity.Flight;
 7 import org.junit.Test;
 8 import org.junit.runner.RunWith;
 9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.test.annotation.Commit;
11 import org.springframework.test.context.ContextConfiguration;
12 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
13 import org.springframework.transaction.annotation.Transactional;
14 
15 import java.util.Date;
16 
17 /**
18  * @version 1.0
19  * @ClassName TestOneTOne
20  * @Description TODO
21  * @Author WSC
22  * @Date 2019/8/20 14:42
23  **/
24 @RunWith(SpringJUnit4ClassRunner.class)//spring框架测试
25 @ContextConfiguration(locations = "classpath:applicationContext.xml") //引入xml配置文件
26 public class TestOneTOne 
27     //自动注入
28     @Autowired
29     private CityDao cityDao;
30     @Autowired
31     private FlightDao flightDao;
32     @Test
33     //事务 必须加
34     @Transactional
35     //提价 必须加
36     @Commit
37     public void test01()
38         //city对象 存数据
39         City city = new City();
40         city.setCityName("上海");
41         //flight 对象 存数据
42         Flight flight = new Flight();
43         flight.setArriveDate(new Date());
44         flight.setFlightNo("123");
45         //配置关联关系
46         city.setFlight(flight);
47         flight.setCity(city);
48         // 保存 入 数据库
49         cityDao.save(city);
50 //        flightDao.save(flight);
51     
52 
test

 

以上是关于表与表关联 一对一的主要内容,如果未能解决你的问题,请参考以下文章

-------------------------------用MyBatis处理表与表之间的关联关系----------------------------------

重修课程day40(mysql四之表与表关联和表操作)

07表与表之间的关系

如何设置SQL数据库表与表的关联关系?

SQL外键foreign key 表与表之间的三种关系

数据库表关系(一堆垛,多对多)