当前位置:网站首页>JPA之使用复合主键
JPA之使用复合主键
2022-08-08 11:44:00 【圆师傅】
1. 目标
在设计数据库表的时候,有时候不想定义没有意义的Id作为主键,就可以使用复合主键。这个时候使用JPA进行操作,应该如何使用复合主键?这里使用@IdClass。
2. 数据库设计
create table if not exists watch(
brand varchar (20),
name varchar (20),
color varchar (20),
stock int ,
primary key (brand, name, color)
)
3. Entity 定义
import org.apache.commons.lang3.StringUtils
import java.io.Serializable
import javax.persistence.*
@Entity
@Table(name = "watch")
@IdClass(WatchIdClass::class)
data class WatchEntity(
@Id
@Column(name = "brand")
val brand: String,
@Id
@Column(name = "name")
val name: String,
@Id
@Column(name = "color")
val color: String,
@Column(name = "stock")
val stock: Int
)
这里了使用了@IdClass注解,可以看到该注解的注释:
Specifies a composite primary key class that is mapped to multiple fields or properties of the entity.
The names of the fields or properties in the primary key class and the primary key fields or properties of the entity must correspond and their types must be the same.
因此这里定义Id class
data class WatchIdClass(
var brand: String = StringUtils.EMPTY,
var name: String = StringUtils.EMPTY,
var color: String = StringUtils.EMPTY
) : Serializable
这个IdClass需要实现Serializable接口。
另外,由于使用的是koltin,需要这个类有默认的无参构造函数,因此加了默认值,这样会生成默认构造函数。
4. 使用
有了上面的定义之后,repository接口就可以正常使用了。这里举了个例子
Repository定义:
interface WatchRepository : JpaRepository<WatchEntity, String> {
fun findByBrandAndNameAndColor(brand: String, name: String, color: String): WatchEntity
}
Service:
@Service
class WatchService @Autowired constructor(private val watchRepository: WatchRepository) {
fun getWatch(brand: String, name: String, color: String): WatchEntity {
return watchRepository.findByBrandAndNameAndColor(brand, name, color)
}
}
5. 源码
上述示例的代码在这里
边栏推荐
猜你喜欢
3 million tenders!Qingdao Medical Security Bureau host database middleware operation and maintenance service project
ReentrantLock原理,ReentrantLock和synchronized区别
皕杰报表之数据校验与处理
Kunpeng Developer Creation Day 2022: Kunpeng Full-Stack Innovation and Developers Build Digital Hunan
移动适配vw/vh方法—vw/vh实例—模拟B站手机端首页—获取样式教程视频
STM32的内存管理相关(内存架构,内存管理,map文件分析)
Hystrix熔断器
Classificition Loss in target detection
学习与尝试 --&gt; 事件风暴
dedecms支持Word图文自动粘贴
随机推荐
Pattern Recognition Study Notes: Chapter 6 Other Classification Methods (Continuously updated...)
关于win下面Celery服务报 Process 'Worker' exited with 'exitcode 1' [duplicate]
PG核心篇--物理存储结构
Mysql索引优化实战
微服务负载均衡器Ribbon实战
学习笔记:CS520 Knowledge Graphs
JVM的GC讲解及调优
小程序使用npm包
Classificition Loss in target detection
LeetCode_487_最大连续1的个数Ⅱ
微服务负载均衡器LoadBalancer实战
2G 3G 4G 5G 基站覆盖范围
五心红娘6月成功案列
皕杰报表之数据校验与处理
MySQL安装及使用
NLP和CV中的Local和Global建模
Thoroughly understand the differences and application scenarios of session, cookie, sessionStorage, and localStorage (interview orientation)
LeetCode_1004_最大连续1的个数Ⅲ
【kali-权限提升】(4.2.4)社会工程学工具包:远控木马使用、设置、利用
模式识别 学习笔记:第六章 其他分类方法 (持续更新中。。。)