JPA之使用复合主键

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. 源码

上述示例的代码在这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值