表之间关系的划分
一对一
一对多:
一的一方:主表
多的一方:从表
外键:需要再从表上新建一列作为外键,他的取值来源于主表的主键
多对多:
中间表:中间表中最少应该由两个字段组成,这两个字段做为外键指向两张表的主键,又组成了联合主键
注意:一对多关系可以看为两种: 即一对多,多对一。
在JPA框架中表关系的分析步骤
在实现了ORM思想的框架中(如JPA),可以让我们通过操作实体类就实现对数据库表的操作。
首先确定两张表之间的关系。
如果关系确定错了,后面做的所有操作就都不可能正确。
在数据库中实现两张表的关系
在实体类中描述出两个实体的关系
配置出实体类和数据库表的关系映射
JPA中的一对多
表关系建立
一对多关系中,我们习惯把一的一方称之为主表,把多的一方称之为从表。在数据库中建立一对多的关系,需要使用数据库的外键约束。
配置文件
加入jpa配置 property
<?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"
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">
<!--spring和springDataJpa的配置-->
<!--1.创建EntityManagerFactory对象交给容器管理 -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--根据配置自动扫描包下的所有类(实体类所在的包) -->
<property name="packagesToScan" value="com.rpf.domain"></property>
<!--配置Jpa的实现方式 persistenceProvider服务的提供者-->
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
</property>
<!--配置jpa的供应商适配器-->
<!--JPA的供应商适配器-->
<property name="jpaVendorAdapter">