SpringDataJPA是Spring Data的一个子项目,通过提供基于JPA的Repository极大的减少了JPA作为数据访问方案的代码量,你仅仅需要编写一个接口集成下SpringDataJPA内部定义的接口即可完成简单的CRUD操作。
本篇文章引导你通过Spring Boot
,Spring Data JPA
和MySQL
实现many-to-many
关联表存在额外字段下关系映射。
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">
4.0.0
cn.merryyou
jpa-example
1.0-SNAPSHOT
one-to-one-foreignkey
one-to-one-primarykey
one-to-many
many-to-many
many-to-many-extra-columns
pom
io.spring.platform
platform-bom
Brussels-SR6
pom
import
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">
jpa-example
cn.merryyou
1.0-SNAPSHOT
4.0.0
many-to-many-extra-columns
UTF-8
1.8
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
org.apache.maven.plugins
maven-compiler-plugin
3.6.1
1.8
1.8
book.id
和 publisher.id
多对多关联表book_publisher
还存在published_data
字段
db.sql
CREATE DATABASE IF NOT EXISTS `jpa_manytomany_extracolumns` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `jpa_manytomany_extracolumns`;
--
-- Table structure for table `book`
--
DROP TABLE IF EXISTS `book`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `book` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `publisher`
--
DROP TABLE IF EXISTS `publisher`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `publisher` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;
--
-- Table structure for table `book_publisher`
--
DROP TABLE IF EXISTS `book_publisher`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `book_publisher` (
`book_id` int(10) unsigned NOT NULL,
`publisher_id` int(10) unsigned NOT NULL,
`published_date` datetime DEFAULT NULL,
PRIMARY KEY (`book_id`,`publisher_id`),
KEY `fk_bookpublisher_publisher_idx` (`publisher_id`),
CONSTRAINT `fk_bookpublisher_book` FOREIGN KEY (`book_id`) REFERENCES `book` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_bookpublisher_publisher` FOREIGN KEY (`publisher_id`) REFERENCES `publisher` (`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;
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<BookPublisher> bookPublishers;
public Book() {
}
public Book(String name) {
this.name = name;
bookPublishers = new HashSet<>();
}
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<BookPublisher> getBookPublishers() {
return bookPublishers;
}
public void setBookPublishers(Set<BookPublisher> bookPublishers) {
this.bookPublishers = bookPublishers;
}
}
@Entity
public class Publisher {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@OneToMany(mappedBy = "publisher")
private Set<BookPublisher> bookPublishers;
public Publisher(){
}
public Publisher(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<BookPublisher> getBookPublishers() {
return bookPublishers;
}
public void setBookPublishers(Set<BookPublisher> bookPublishers) {
this.bookPublishers = bookPublishers;
}
}
@Entity
@Table(name = "book_publisher")
public class BookPublisher implements Serializable {
@Id
@ManyToOne
@JoinColumn(name = "book_id")
private Book book;
@Id
@ManyToOne
@JoinColumn(name = "publisher_id")
private Publisher publisher;
@Column(name = "published_date")
private Date publishedDate;
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
}
@Table
声明此对象映射到数据库的数据表,通过它可以为实体指定表(talbe),目录(Catalog)和schema的名字。该注释不是必须的,如果没有则系统使用默认值(实体的短类名)。@Id
声明此属性为主键。该属性值可以通过应该自身创建,但是Hibernate推荐通过Hibernate生成@GeneratedValue
指定主键的生成策略。
@Column
声明该属性与数据库字段的映射关系。@OneToMany
一对多关联关系@ManyToMany
多对多关联关系@JoinColumn
指定关联的字段@JoinTable
参考public interface BookRepository extends JpaRepository<Book, Integer> {
}
public interface PublisherRepository extends JpaRepository<Publisher, Integer> {
}
Spring Data JPA
包含了一些内置的Repository
,实现了一些常用的方法:findone
,findall
,save
等。
spring:
datasource:
url: jdbc:mysql://localhost/jpa_manytomany_extracolumns
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 BookRepositoryTest {
@Autowired
private BookRepository bookRepository;
@Autowired
private PublisherRepository publisherRepository;
@Test
@Transactional
public void manyToManyExtraColumnsTest() throws Exception{
Book bookA = new Book("Book One");
Publisher publisherA = new Publisher("Publisher One");
BookPublisher bookPublisher = new BookPublisher();
bookPublisher.setBook(bookA);
bookPublisher.setPublisher(publisherA);
bookPublisher.setPublishedDate(new Date());
bookA.getBookPublishers().add(bookPublisher);
publisherRepository.save(publisherA);
bookRepository.save(bookA);
// test
System.out.println(bookA.getBookPublishers().size());
// update
bookA.getBookPublishers().remove(bookPublisher);
bookRepository.save(bookA);
// test
System.out.println(bookA.getBookPublishers().size());
}
}
从我的 github 中下载,https://github.com/longfeizheng/jpa-example/tree/master/many-to-many-extra-columns
???关注微信小程序java架构师历程 上下班的路上无聊吗?还在看小说、新闻吗?不知道怎样提高自己的技术吗?来吧这里有你需要的java架构文章,1.5w+的java工程师都在看,你还在等什么?