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

上述示例的代码在这里

猜你喜欢

转载自blog.csdn.net/Apple_wolf/article/details/126207812