pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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>cn.dy</groupId>
<artifactId>springJpaOneToOne</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<spring.version>4.2.4.RELEASE</spring.version>
<hibernate.version>5.0.7.Final</hibernate.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<c3p0.version>0.9.1.2</c3p0.version>
<mysql.version>5.1.6</mysql.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--spring start-->
<!--spring aop-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring aop-->
<!--spring ioc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring ioc-->
<!--spring end-->
<!--spring 对orm框架的支持包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring 对orm框架的支持包-->
<!--hibernate start-->
<!--hibernate 核心包-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!--hibernate 对JPA实现的包-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!--hibernate 验证包-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
</dependency>
<!--hibernate end-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--mysql的驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--spring dataJpa 的坐标-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<!--spring 测试 的坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- el 标签 的坐标-->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
<!-- el 标签 的坐标-->
</dependencies>
</project>
resources:
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: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"
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">
<!--1 创建数据库的连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="password" value="root"/>
<property name="user" value="root"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_data?characterEncoding=utf-8"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</bean>
<!--2 工厂类对象-->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!--数据源-->
<property name="dataSource" ref="dataSource"/>
<!--实体类的扫描器-->
<property name="packagesToScan" value="cn.dy.jpa.entity"/>
<!--jpa配置供应商的适配器-->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- 指定数据库类型-->
<property name="database" value="MYSQL"/>
<!-- 是否自动创建数据库表-->
<property name="generateDdl" value="false"/>
<!-- 数据库方言 支持的特有语法-->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
<!--是否向控制台输出语句 update hibernate.hbm2ddl.auto-->
<property name="showSql" value="true"/>
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!--配置事物-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--一般出现在sevice层 start-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--aop-->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* cn.dy.jpa.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>
<!--一般出现在sevice层 end-->
<!-- <context:component-scan base-package="cn.dy.jpa"></context:component-scan>-->
<!-- dao-->
<jpa:repositories base-package="cn.dy.jpa.dao"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory"/>
</beans>
entity:
Tea主表:
package cn.dy.jpa.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* author:dingyi
* time:2019/8/20 0020 14:57
*/
// 声明该类是jpa的实体类
@Entity
@Table(name = "cust_tea")
public class Tea implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
@Column(name="tea_id")
private long teaId;
@Column(name="tea_name")
private String teaName;
@Column(name="tea_sex")
private String teaSex;
@Column(name="tea_age")
private String teaAge;
@Column(name="tea_Job")
private String teaJob;
// 配置教师与学生之间的关系 (一对多关系)
/**
* 使用注解的形式配置多表关系
* 1.声明关系
* @OneToMany; 配置一对多关系
* 2.配置外键(中间表)
* @JoinColumn:配置外键
* name 外键字段名称
* referencedColumnName:参照的主表字段名称
* 在教师实体类上(一的一方)添加了外键配置,所以对于学生而言,也具备了维护外键的作用
*/
@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
// @JoinColumn(name = "teaid",referencedColumnName = "tea_id")
private Set<Stu> Stus=new HashSet<>();
public long getTeaId() {
return teaId;
}
public void setTeaId(long teaId) {
this.teaId = teaId;
}
public String getTeaName() {
return teaName;
}
public void setTeaName(String teaName) {
this.teaName = teaName;
}
public String getTeaSex() {
return teaSex;
}
public void setTeaSex(String teaSex) {
this.teaSex = teaSex;
}
public String getTeaAge() {
return teaAge;
}
public void setTeaAge(String teaAge) {
this.teaAge = teaAge;
}
public String getTeaJob() {
return teaJob;
}
public void setTeaJob(String teaJob) {
this.teaJob = teaJob;
}
public Set<Stu> getStus() {
return Stus;
}
public void setStus(Set<Stu> stus) {
Stus = stus;
}
@Override
public String toString() {
return "Tea{" +
"teaId=" + teaId +
", teaName='" + teaName + '\'' +
", teaSex='" + teaSex + '\'' +
", teaAge='" + teaAge + '\'' +
", teaJob='" + teaJob + '\'' +
'}';
}
}
Stu从表:
package cn.dy.jpa.entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* author:dingyi
* time:2019/8/20 0020 17:32
*/
@Entity
@Table(name = "cust_stu")
public class Stu implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
@Column(name = "stu_id")
private Long stuId;
@Column(name = "stu_name")
private String stuName;
@Column(name = "stu_sex")
private String stuSex;
@Column(name = "stu_age")
private String stuAge;
/**
* 配置学生到教师的多对一关系
* 使用注解的形式配置多对一关系
* 1.配置表关系
* @ManyToOne: 配置多对一关系
* 2.配置外键(中间表)
* 配置外键的过程,配置到了多的一方,就会再多的一方维护外键
*/
@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name = "stuid",referencedColumnName = "tea_id")
private Tea tea;
public Long getStuId() {
return stuId;
}
public void setStuId(Long stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuSex() {
return stuSex;
}
public void setStuSex(String stuSex) {
this.stuSex = stuSex;
}
public String getStuAge() {
return stuAge;
}
public void setStuAge(String stuAge) {
this.stuAge = stuAge;
}
public Tea getTea() {
return tea;
}
public void setTea(Tea tea) {
this.tea = tea;
}
@Override
public String toString() {
return "Stu{" +
"stuId=" + stuId +
", stuName='" + stuName + '\'' +
", stuSex='" + stuSex + '\'' +
", stuAge='" + stuAge + '\'' +
'}';
}
}
TeaDao:
package cn.dy.jpa.dao;
/**
* author:dingyi
* time:2019/8/20 0020 18:43
*/
import cn.dy.jpa.entity.Tea;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface TeaDao extends JpaRepository<Tea,Long>, JpaSpecificationExecutor<Tea> {
}
StuDao:
package cn.dy.jpa.dao;
import cn.dy.jpa.entity.Stu;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* author:dingyi
* time:2019/8/20 0020 18:48
*/
public interface StuDao extends JpaRepository<Stu,Long>, JpaSpecificationExecutor<Stu> {
}
test测试1:
import cn.dy.jpa.dao.StuDao;
import cn.dy.jpa.dao.TeaDao;
import cn.dy.jpa.entity.Stu;
import cn.dy.jpa.entity.Tea;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Commit;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
/**
* author:dingyi
* time:2019/8/20 0020 19:17
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:applicationContext.xml")
public class testOneToMany {
@Autowired
TeaDao teaDao;
@Autowired
StuDao stuDao;
/**
* 保存一个教师,一个学生
*
*/
@Test
@Transactional //配置事务
@Commit
@Rollback(false) //不自动回滚
public void testAdd(){
//创建一个教师,创建一个学生
Tea tea = new Tea();
tea.setTeaName("吉泽明步");
tea.setTeaAge("34");
tea.setTeaSex("女");
tea.setTeaJob("教师");
Stu stu1 = new Stu();
stu1.setStuName("张敏");
stu1.setStuSex("女");
stu1.setStuAge("32");
Stu stu2 = new Stu();
stu2.setStuName("思思");
stu2.setStuSex("女");
stu2.setStuAge("33");
tea.getStus().add(stu1);
tea.getStus().add(stu2);
stu1.setTea(tea);
stu2.setTea(tea);
teaDao.save(tea);
stuDao.save(stu1);
stuDao.save(stu2);
}
}
test测试2:
import cn.dy.jpa.dao.StuDao;
import cn.dy.jpa.dao.TeaDao;
import cn.dy.jpa.entity.Stu;
import cn.dy.jpa.entity.Tea;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Commit;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Set;
/**
* author:dingyi
* time:2019/8/21 0021 16:24
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:applicationContext.xml")
public class ObJQuerytest {
@Autowired
TeaDao teaDao;
@Autowired
StuDao stuDao;
/**
* could not initialize proxy - no Session 报错原因: @Transactional
*/
@Test
@Transactional
@Commit
@Rollback(false)
public void testQuery(){
//查询id为1的教师
Tea teaDaoOne = teaDao.getOne(1L);
//对象导航查询,此教师下的所有学生
Set<Stu> stus = teaDaoOne.getStus();
for (Stu stu:stus){
System.out.println(stu);
}
}
}