010_Spring Data JPA一对多关系

1. 一对多的关联关系

1.1. 角色和用户是一对多的关联关系

角色类(对应表名: t_role): 一方

用户类(对应表名: t_user): 多方

1.2. 角色表

1.3. 用户表 

2. 一对多的关联关系例子

2.1. 创建一个名为spring-data-jpa-one2many的Java项目, 同时添加相关jar包, 并添加JUnit能力。

 

2.2. 新建Role.java 

package com.bjbs.pojo;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity // 指定该类是实体类
@Table(name = "t_role") // 指定数据库表名(表名和实体类对应)
public class Role implements Serializable {
	private static final long serialVersionUID = 1L;
	
	@Id // 指定为主键
	@GeneratedValue(strategy = GenerationType.IDENTITY) // 指定主键生成策略
	@Column(name = "id") // 指定表中列名(列名和属性名对应)
	private Integer id;

	@Column(name = "name")
	private String name; // 角色名
	
	@OneToMany(mappedBy="role")
	private Set<User> users = new HashSet<User>();

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set<User> getUsers() {
		return users;
	}

	public void setUsers(Set<User> users) {
		this.users = users;
	}

	@Override
	public String toString() {
		return "Role [id=" + id + ", name=" + name + "]";
	}
	
}

2.3. 新建User.java

package com.bjbs.pojo;

import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity // 指定该类是实体类
@Table(name = "t_user") // 指定数据库表名(表名和实体类对应)
public class User implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id // 指定为主键
	@GeneratedValue(strategy = GenerationType.IDENTITY) // 指定主键生成策略
	@Column(name = "id") // 指定表中列名(列名和属性名对应)
	private Integer id;

	@Column(name = "name")
	private String name; // 用户名

	@ManyToOne(cascade=CascadeType.PERSIST)
	// @JoinColumn: 就是维护一个外键
	@JoinColumn(name="r_id")
	private Role role;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + "]";
	}

}

2.4. 新建UserRepository.java

package com.bjbs.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import com.bjbs.pojo.User;

/**
 * 参数一T: 当前需要映射的实体; 参数二 T: 当前映射的实体中的id的类型
 */
public interface UserRepository extends JpaRepository<User, Integer> {

}

2.5. 新建TestUserRepository.java

package com.bjbs.test;

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 com.bjbs.dao.UserRepository;
import com.bjbs.pojo.Role;
import com.bjbs.pojo.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestUserRepository {
	@Autowired
	private UserRepository userRepository;
	
	@Test
	public void findOne() {
		User user = userRepository.findOne(2);
		System.out.println(user);
		Role role = user.getRole();
		System.out.println(role);
	}
	
	@Test
	public void save() {
		// 新建用户
		User user = new User();
		user.setName("翠花");

		// 新建角色
		Role role = new Role();
		role.setName("测试人员");
		
		// 建立关系
		role.getUsers().add(user);
		user.setRole(role);
		
		// 保存用户
		userRepository.save(user);
	}
}

2.6. 在src下新建application.properties

spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.25.138:3306/StudyMybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=lyw123456

2.7. 在src下新建applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
	
	<!-- 配置读取properties文件的工具类 -->
	<context:property-placeholder location="classpath:application.properties" />

	<!-- 配置c3p0数据库连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="${spring.datasource.url}" />
		<property name="driverClass" value="${spring.datasource.driverClassName}" />
		<property name="user" value="${spring.datasource.username}" />
		<property name="password" value="${spring.datasource.password}" />
	</bean>

	<!-- Spring整合JPA 配置EntityManagerFactory -->
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<!-- hibernate相关的属性的注入 -->
				<!-- 配置数据库类型 -->
				<property name="database" value="MYSQL" />
				<!-- 正向工程 自动创建表 -->
				<!-- <property name="generateDdl" value="true" /> -->
				<!-- 显示执行的SQL -->
				<property name="showSql" value="true" />
			</bean>
		</property>
		<!-- 扫描实体的包 -->
		<property name="packagesToScan">
			<list>
				<value>com.bjbs.pojo</value>
			</list>
		</property>
	</bean>

	<!-- 配置Hibernate的事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>

	<!-- 配置开启注解事务处理 -->
	<tx:annotation-driven transaction-manager="transactionManager" />

	<!-- 配置springIOC的注解扫描 -->
	<context:component-scan base-package="com.bjbs.service" />

	<!-- Spring Data JPA 的配置 -->
	<!-- base-package: 扫描dao接口所在的包 -->
	<jpa:repositories base-package="com.bjbs.dao" />
</beans>

2.8. 查询一个用户

2.9. 保存一个用户 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值