• 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)
    )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    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
    )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    这里了使用了@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
    
    • 1
    • 2
    • 3
    • 4
    • 5

    这个IdClass需要实现Serializable接口。
    另外,由于使用的是koltin,需要这个类有默认的无参构造函数,因此加了默认值,这样会生成默认构造函数。

    4. 使用

    有了上面的定义之后,repository接口就可以正常使用了。这里举了个例子
    Repository定义:

    interface WatchRepository : JpaRepository<WatchEntity, String> {
        fun findByBrandAndNameAndColor(brand: String, name: String, color: String): WatchEntity
    }
    
    • 1
    • 2
    • 3

    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)
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    5. 源码

    上述示例的代码在这里

  • 相关阅读:
    Redis篇(5)——持久化
    uni-app开发
    conda不同环境pip list包都一样问题;conda国内镜像加速
    ThreeJS-3D教学十-有宽度的line
    【Docker】——容器数据卷
    从REST到GraphQL:升级你的Apollo体验
    第10章、对象和类
    【概率论与数理统计】第二章知识点复习与习题
    扩容领跑者 Arbitrum 抢占 Layer3 竞争高地
    Rime 如何通过 iCloud 实现词库多端同步,Windows、iOS、macOS
  • 原文地址:https://blog.csdn.net/Apple_wolf/article/details/126207812