导入依赖
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.10.Final</version>
</dependency>
<!-- mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<!-- 连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.18</version>
<scope>test</scope>
</dependency>
customer实体类
package com.li.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Entity//作为hibernate实体类
@Table(name="customer")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "custId")
private Long custId;//客户主键
@Column(name = "custName")
private String custName;//客户名称
@Column(name = "custAddress")
private String custAddress;//客户地址
//单向关联 一对一
/**cascade 设置关联操作
* ALL 所有持久化操作
* PERSIST 只有插入才会执行关联操作
* MERGE 只有修改才会执行关联操作
* REMOVE 只有删除才会执行关联操作
* fetch是否懒加载
* LAZY 懒加载(直到用到对象才会进行查询)
* EAGER立即加载(默认)
* (cascade = CascadeType.ALL,fetch = FetchType.LAZY)
* orphanRemoval = true 关联移除(通常在修改的时候会用到)
* 一旦把关联的数据设置为null,或者修改为其他关联数据
* 如果想要删除关联数据,就可以设置为true
* optional = false 关联对象不能为null 默认为true 即可以为空
* mappedBy 将外键约束给另一方维护 值 = 另一方关联属性名(通常在双向关联关系中,会放弃一方的外键约束)
*/
@OneToOne(cascade = CascadeType.ALL)
//设置外键的字段名
@JoinColumn(name = "aid")
private Account account;
}
?account实体类
package com.li.pojo;
import lombok.*;
import javax.persistence.*;
@Entity
@Data// 相当于写了 @Getter //@Getter @Setter @RequiredArgsConstructor @EqualsAndHashCode
// 生成所有属性的get方法
//@Setter//生成所有属性的set方法
//@RequiredArgsConstructor//生成所有属性的get方法
//@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "account")
public class Account {
@Id
@Column(name = "aid")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long aid;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
/*双向关联
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "id")
private Customer customer;*/
}
接口
package com.li.repositories;
import com.li.pojo.Customer;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface CustomerRepository extends PagingAndSortingRepository<Customer,Long> {
}
配置类
package com.li.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@Configuration //标记当前类为配置类 相当于xml配置
@EnableJpaRepositories(basePackages = "com.li.repositories")
//启动 jpa 相当于<jpa:repositories base-package="com.li.repositories"
@EnableTransactionManagement //开启事务
public class SpringDataJPAConfig {
/*
<bean class="com.alibaba.druid.pool.DruidDataSource" name="dataSource">
<property name="username" value="root"></property>
<property name="password" value="root"></property>
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" ></property>
<property name="url" value="jdbc:mysql://localhost:3306/sprindataJpa?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true" ></property>
</bean>
*/
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mysql://localhost:3306/sprindataJpa?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true");
dataSource.setUsername("root");
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setPassword("root");
return dataSource;
}
/*
<bean name="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<!-- Hibernate实例-->
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- 生成数据库表-->
<property name="generateDdl" value="true"></property>
<property name="showSql" value="true"></property>
</bean>
</property>
<!-- 设置实体类的包名-->
<property name="packagesToScan" value="com.li.pojo"></property>
<property name="dataSource" ref="dataSource">
<!-- 可以用这种写法 <bean></bean>-->
</property>
</bean>
*/
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.li.pojo");
factory.setDataSource(dataSource());
return factory;
}
/*
<bean class="org.springframework.orm.jpa.JpaTransactionManager" name="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
*/
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
return txManager;
}
}
测试类
package com.li;
import com.li.config.SpringDataJPAConfig;
import com.li.pojo.Account;
import com.li.pojo.Customer;
import com.li.repositories.CustomerRepository;
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 org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
@ContextConfiguration(classes = SpringDataJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class OneToOneTest {
@Autowired
CustomerRepository repository;
@Test//插入
public void testC() {
Account account = new Account();
account.setPassword("123");
account.setUsername("admin");
Customer customer = new Customer();
customer.setCustName("张三");
customer.setCustAddress("郑州");
customer.setAccount(account);
repository.save(customer);
}
@Test//查询
//为什么要配置事务:
//当通过repository 调用完查询方法,session就会立即关闭,一旦session关闭你就不能查询
//加了事务后,就能让session直到事务方法执行完毕之后才关闭
@Transactional(readOnly = true)
public void testR() {
Optional<Customer> byId = repository.findById(1L);// 只查询客户,session关闭
System.out.println("==============");
System.out.println(byId.get());
}
@Test
public void testD() {
repository.deleteById(3L);
}
@Test
public void testU() {
Customer customer = new Customer();
customer.setCustId(1L);
customer.setCustName("xxx");
customer.setAccount(null);
repository.save(customer);
}
}
?
?
?
|