以公司和部门为例,一对多多对一关系
sql语句
CREATE TABLE `enterprise` ( `id` int(11) NOT NULL AUTO_INCREMENT, `enterpriseName` varchar(255) DEFAULT NULL COMMENT '企业名称', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; CREATE TABLE `dept` ( `id` int(11) NOT NULL AUTO_INCREMENT, `deptName` varchar(255) DEFAULT NULL COMMENT '部门名称', `eid` int(11) DEFAULT NULL COMMENT '企业编号', PRIMARY KEY (`id`), KEY `eid` (`eid`), CONSTRAINT `dept_ibfk_1` FOREIGN KEY (`eid`) REFERENCES `enterprise` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;pom依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.vladmihalcea</groupId> <artifactId>hibernate-types-5</artifactId> <version>2.4.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.5</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency>application文件
server: port: 9999 spring: application: name: springboot-jpa datasource: type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://localhost:3306/xxxx?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconect=true&serverTimezone=GMT%2b8 username: xxxx password: xxxx driver-class-name: com.mysql.jdbc.Driver filters: stat maxActive: 50 initialSize: 0 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 1 from dual testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20 removeAbandoned: true removeAbandonedTimeout: 180 jpa: show-sql: true hibernate: naming: physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl ddl-auto: update properties: hibernate: format_sql: true show_sql: true current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext dialect: org.hibernate.dialect.MySQL5Dialect实体类
/** * @Description * @Author zgc * @Date 2020-10-05 */ @Entity @Table ( name ="dept" ) @DynamicInsert(true) @DynamicUpdate(true) public class Dept implements Serializable { private static final long serialVersionUID = 1L; @Id //代表主键自增长 @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id" ) private Integer id; /**部门名称*/ @Column(name = "deptName" ) private String deptName; /**企业编号*/ //多的一方可以级联保存,保存部门的同时保存公司 @ManyToOne(cascade = CascadeType.PERSIST) //管理外键名称 @JoinColumn(name = "eid") private Enterprise enterprise; get set ... /** * @Description * @Author zgc * @Date 2020-10-05 */ @Entity @Table ( name ="enterprise" ) @DynamicInsert(true) @DynamicUpdate(true) public class Enterprise implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id" ) private Integer id; /**企业名称*/ @Column(name = "enterpriseName" ) private String enterpriseName; //一的一方,mappedBy:部门外键字段名称 @OneToMany(mappedBy = "enterprise") private Set<Dept> deptSet = new HashSet<>(); get set ... }编写测试类
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = TmpApplication.class) public class JpaTest { @Autowired private DeptRepository deptRepository; @Test public void add(){ //创建一个企业 Enterprise enterprise = new Enterprise(); enterprise.setEnterpriseName("腾讯"); //创建一个部门 Dept dept = new Dept(); dept.setDeptName("人事部"); //关联 enterprise.getDeptSet().add(dept); dept.setEnterprise(enterprise); //保存 this.deptRepository.save(dept); } @Test public void find(){ Dept dept = deptRepository.findById(1).get(); //打印部门名称 System.out.println(dept.getDeptName()); //打印部门关联的企业名称 System.out.println(dept.getEnterprise().getEnterpriseName()); }至此一个JPA简单的多表关联操作就完成了。有什么问题欢迎评论区指出
