远程关联
警告
远程关联是Jimmer和微服务技术体系相结合后的产物,会在Spring Cloud和远程关联中详细介绍。
本文的目的并非系统性讲解远程关联,仅仅介绍远程关联所需映射配置。
@Entity
@Entity
注解具备可选参数microServiceName
,默认为""。
关联属性涉及两个实体类型,因为关联必然从源头方指向目标方 (自关联属性比较特殊,源头方和目标方重合)
-
如果关联属性的源实体和目标实体的
microServiceName
相等,则该关联为本地关联 (本文之前所有例子中的实体都采用默认的microServiceName
,因此都是本地关联) -
如果关联属性的源实体和目标实体的
microServiceName
不相等,则该关联为远程关联。
例如
-
主动方 (必需):
Book.authors
- Java
- Kotlin
Book.java@Entity(microServiceName = "book-service")
public interface Book {
@ManyToMany
List<Author> authors();
...省略其他代码...
}Book.kt@Entity(microServiceName = "book-service")
interface Book {
@ManyToMany
val authors: List<Author>
...省略其他代码...
} -
从动方 (可选):
Author.authors
- Java
- Kotlin
Author.java@Entity(microServiceName = "author-service")
public interface Author {
@ManyToMany(mappedBy = "authors")
List<Book> books();
...省略其他代码...
}Author.kt@Entity(microServiceName = "author-service")
interface Author {
@ManyToMany(mappedBy = "authors")
val books: List<Book>
...省略其他代码...
}
这里,Book
的微服务名为book-service
,Author
的微服务名为author-service
。二者不相等,因此Book.authors
和Author.books
都是远程关联
@MappedSuperclass
作为超类型的MappedSuperclass
有两种用法
-
可以包含关联属性,但必需隶属于同一个微服务
- Java
- Kotlin
BookServiceCommonEntity.java@MappedSuperclass(microServiceName = "book-service")
public interface BookServiceCommonEntity {
LocalDateTime createdTime();
@ManyToOne
User createdBy();
LocalDateTime modifiedTime();
@ManyToOne
User modifiedBy();
}BookServiceCommonEntity.kt@MappedSuperclass(microServiceName = "book-service")
interface BookServiceCommonEntity {
val createdTime: LocalDateTime
@ManyToOne
val createdBy: User
val modifiedTime: LocalDateTime
@ManyToOne
val modifiedBy: User
}这里
BookServiceCommonEntity
具备关联属性createdBy
和modifiedBy
,但是只有同属于微服务"book-service"的Entity
或其他MappedSuperclass
才可以继承它。 -
跨越任何微服务,但不得包含关联属性
- Java
- Kotlin
CommonEntity.java@MappedSuperclass(acrossMicroServices = true)
public interface CommonEntity {
LocalDateTime createdTime();
LocalDateTime modifiedTime();
}CommonEntity.kt@MappedSuperclass(acrossMicroServices = true)
interface CommonEntity {
val createdTime: LocalDateTime
val modifiedTime: LocalDateTime
}