需求:从角色到用户的一对多的关联关系
角色:一方
用户:多方
创建项目09-spring-data-jpa-onetomany
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bjsxt</groupId>
<artifactId>09-spring-data-jpa-onetomany</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<spring.version>4.3.23.RELEASE</spring.version>
<hibernate.version>5.1.17.Final</hibernate.version>
<mysql.version>5.1.47</mysql.version>
<c3p0.version>0.9.2.1</c3p0.version>
<junit.version>4.12</junit.version>
<lombok.version>1.18.6</lombok.version>
<hibernate-entitymanager.version>5.0.7.Final</hibernate-entitymanager.version>
<spring-data-jpa.version>1.7.0.RELEASE</spring-data-jpa.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/spring-data-test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
#jdbc.url=jdbc:mysql://localhost:3306/spring-data-test 这个保存到数据库中会导致乱码
jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=123456
applicationContext.xml
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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 https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.11.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 配置读取properties文件的工具类 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置c3p0数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="driverClass" value="${jdbc.driver.class}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.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.bjsxt.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.bjsxt"></context:component-scan>
<!-- Spring Data JPA的配置 base-package扫描dao接口所在的包 -->
<jpa:repositories base-package="com.bjsxt.dao"></jpa:repositories>
</beans>
1 编写实体类
package com.bjsxt.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="ts_users")
public class Users implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Long id;
@Column(name="user_name")
private String userName;
@Column(name="age")
private Integer age;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "role_id")
private Roles roles;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Roles getRoles() {
return roles;
}
public void setRoles(Roles roles) {
this.roles = roles;
}
@Override
public String toString() {
return "Users [id=" + id + ", userName=" + userName + ", age=" + age + "]";
}
}
package com.bjsxt.pojo;
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;
/**
*
* @author guozi
*
*/
@Entity
@Table(name = "ts_roles")
public class Roles {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "role_id")
private Long roleId;
@Column(name = "role_name")
private String roleName;
// mappedBy:users中指定的roles属性
@OneToMany(mappedBy = "roles")
private Set<Users> users = new HashSet<>();
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Set<Users> getUsers() {
return users;
}
public void setUsers(Set<Users> users) {
this.users = users;
}
@Override
public String toString() {
return "Roles [roleId=" + roleId + ", roleName=" + roleName + "]";
}
}
2 创建dao接口
package com.bjsxt.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.bjsxt.pojo.Users;
/**
* JpaRepository接口使用
* JpaRepository是开发中使用最多的接口
* @author guozi
*
*/
public interface UsersDao extends JpaRepository<Users, Long> {
}
3 创建测试类
package com.bjsxt.dao;
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.bjsxt.pojo.Roles;
import com.bjsxt.pojo.Users;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class OneToManyTest {
@Autowired
private UsersDao usersDao;
/**
* 保存
* Hibernate: insert into ts_roles (role_name) values (?)
Hibernate: insert into ts_users (age, role_id, user_name) values (?, ?, ?)
注意:此处如果实体类用的时lombok时,会报java.lang.StackOverflowError异常,所以将原有的使用lombok去掉,改成setter和getter及toString处理,
请参考https://www.jianshu.com/p/d6bb1c343146
*/
@Test
public void test() {
// 创建角色
Roles role = new Roles();
role.setRoleName("船员");
// 创建用户
Users user = new Users();
user.setAge(10);
user.setUserName("乔巴");
// 建立关系
user.setRoles(role);
role.getUsers().add(user);
// 保存数据
this.usersDao.save(user);
}
/**
* 查询
* Hibernate: select users0_.id as id1_1_0_, users0_.age as age2_1_0_, users0_.role_id as role_id4_1_0_, users0_.user_name as user_nam3_1_0_, roles1_.role_id as role_id1_0_1_, roles1_.role_name as role_nam2_0_1_ from ts_users users0_ left outer join ts_roles roles1_ on users0_.role_id=roles1_.role_id where users0_.id=?
Users [id=15, userName=乔巴, age=10]
Roles [roleId=2, roleName=船员]
*/
@Test
public void test2 () {
Users users = this.usersDao.findOne(15l);
System.out.println(users);
System.out.println(users.getRoles());
}
}