SpringDataJPA是Spring Data的一个子项目,通过提供基于JPA的Repository极大的减少了JPA作为数据访问方案的代码量,你仅仅需要编写一个接口集成下SpringDataJPA内部定义的接口即可完成简单的CRUD操作。
本篇文章引导你通过Spring Boot
,Spring Data JPA
和MySQL
实现one-to-many
和many-to-one
关联映射。
<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.0modelVersion>
<groupId>cn.merryyougroupId>
<artifactId>jpa-exampleartifactId>
<version>1.0-SNAPSHOTversion>
<modules>
<module>one-to-one-foreignkeymodule>
<module>one-to-one-primarykeymodule>
<module>one-to-manymodule>
<module>many-to-manymodule>
<module>many-to-many-extra-columnsmodule>
modules>
<packaging>pompackaging>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.spring.platformgroupId>
<artifactId>platform-bomartifactId>
<version>Brussels-SR6version>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
project>
<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">
<parent>
<artifactId>jpa-exampleartifactId>
<groupId>cn.merryyougroupId>
<version>1.0-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>one-to-manyartifactId>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.6.1version>
<configuration>
<source>1.8source>
<target>1.8target>
configuration>
plugin>
plugins>
build>
project>
book.book-category_id
和 book_category.id
db.sql
CREATE DATABASE IF NOT EXISTS `jpa_onetomany`;
USE `jpa_onetomany`;
--
-- Table structure for table `book_detail`
--
DROP TABLE IF EXISTS `book_category`;
CREATE TABLE `book_category` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`,`name`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
--
-- Table structure for table `book`
--
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`book_category_id` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_book_bookcategoryid_idx` (`book_category_id`),
CONSTRAINT `fk_book_bookcategoryid` FOREIGN KEY (`book_category_id`) REFERENCES `book_category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@ManyToOne
@JoinColumn(name = "book_category_id")
private BookCategory bookCategory;
public Book() {
}
public Book(String name) {
this.name = name;
}
public Book(String name, BookCategory bookCategory) {
this.name = name;
this.bookCategory = bookCategory;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BookCategory getBookCategory() {
return bookCategory;
}
public void setBookCategory(BookCategory bookCategory) {
this.bookCategory = bookCategory;
}
}
@Entity
@Table(name = "book_category")
public class BookCategory {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@OneToMany(mappedBy = "bookCategory", cascade = CascadeType.ALL)
private Set books;
public BookCategory(){
}
public BookCategory(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set getBooks() {
return books;
}
public void setBooks(Set books) {
this.books = books;
}
@Override
public String toString() {
String result = String.format(
"Category[id=%d, name='%s']%n",
id, name);
if (books != null) {
for(Book book : books) {
result += String.format(
"Book[id=%d, name='%s']%n",
book.getId(), book.getName());
}
}
return result;
}
}
@Table
声明此对象映射到数据库的数据表,通过它可以为实体指定表(talbe),目录(Catalog)和schema的名字。该注释不是必须的,如果没有则系统使用默认值(实体的短类名)。@Id
声明此属性为主键。该属性值可以通过应该自身创建,但是Hibernate推荐通过Hibernate生成@GeneratedValue
指定主键的生成策略。
@Column
声明该属性与数据库字段的映射关系。
@OneToMany
一对多关联关系@ManyToOne
多对一关联关系@JoinColumn
指定关联的字段public interface BookCategoryRepository extends JpaRepository<BookCategory, Integer> {
}
Spring Data JPA
包含了一些内置的Repository
,实现了一些常用的方法:findone
,findall
,save
等。
spring:
datasource:
url: jdbc:mysql://localhost/jpa_onetomany
username: root
password: admin
driver-class-name: com.mysql.jdbc.Driver
jpa:
show-sql: true
properties:
hibernate:
enable_lazy_load_no_trans: true
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class BookCategoryRepositoryTest {
@Autowired
private BookCategoryRepository repository;
@Test
public void saveCategoryTest(){
BookCategory categoryOne = new BookCategory("Category One");
Set books = new HashSet(){{
add(new Book("Book One", categoryOne));
add(new Book("Book Two", categoryOne));
add(new Book("Book Three", categoryOne));
}};
categoryOne.setBooks(books);
BookCategory categoryTwo = new BookCategory("Category Two");
Set bookBs = new HashSet(){{
add(new Book("Book Four", categoryTwo));
add(new Book("Book Five", categoryTwo));
add(new Book("Book Six", categoryTwo));
}};
categoryTwo.setBooks(bookBs);
Set allBooks = new HashSet();
allBooks.add(categoryOne);
allBooks.add(categoryTwo);
List list = repository.save(allBooks);
Assert.assertNotNull(list);
}
@Test
public void findAll() throws Exception{
for (BookCategory bookCategory : repository.findAll()) {
log.info(bookCategory.toString());
}
}
}
从我的 github 中下载,https://github.com/longfeizheng/jpa-example/tree/master/one-to-many
������关注微信小程序java架构师历程
上下班的路上无聊吗?还在看小说、新闻吗?不知道怎样提高自己的技术吗?来吧这里有你需要的java架构文章,1.5w+的java工程师都在看,你还在等什么?