当前位置:网站首页>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. 源码
上述示例的代码在这里
边栏推荐
猜你喜欢

鲲鹏开发者创享日2022:鲲鹏全栈创新 与开发者共建数字湖南

#yyds Dry Goods Inventory#【Yugong Series】August 2022 Go Teaching Course 005-Variable

软件测试之测试代表用户

day02 -DOM - advanced events (register events, event listeners, delete events, DOM event flow, event objects, prevent default behavior, prevent event bubbling, event delegation) - commonly used mouse

如何使用shell来进行版本管理-以iptables为例

《show your work》 从现在开始!

neural network classification

MySQL----索引

Postman使用简单演示

ReentrantLock原理,ReentrantLock和synchronized区别
随机推荐
leetcode 1584. 连接所有点的最小费用
Software testing testing on behalf of the user
大缓存更强劲,搭载AMD Milan-X的浪潮GPU服务器NF5468A5深度评测
产品-Axure9英文版,下拉框Droplist的条件选择,显示不同内容面板
(原创)[C#] GDI+ 之鼠标交互:原理、示例、一步步深入、性能优化
八、排序与搜索
关于那些我们都听过的营销工具—优惠券
Mobile adaptation method of vw/vh - vw/vh instance - analog B stand mobile home page - get style tutorial video
TF-GNN踩坑记录(一)
五心红娘6月成功案列
Hystrix熔断器
ReentrantLock源码分析和使用案例
爱可可AI前沿推介(8.8)
【AI系统前沿动态第45期】Hinton:深度学习的下一个大事件;一块GPU训练TB级推荐模型不是梦;AI-GPU显存优化发展史
.NET Community Toolkit 8.0.0 版本发布
LeetCode_487_最大连续1的个数Ⅱ
鲲鹏开发者创享日2022:鲲鹏全栈创新 与开发者共建数字湖南
SCCM2012R2管理之版本更新
学习与尝试 --&gt; 事件风暴
Combining "xPlus" to discuss the innovation and change of software architecture