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

    上述示例的代码在这里

  • 相关阅读:
    从零开始配置 vim(8)——文件类型检测
    IDEA 03 (动态sql和分页)
    MySQL 分组排序后 → 如何取前N条或倒数N条
    Dubbo-Activate实现原理
    Python二级题:MOOC学校名单|关键词提取和查找
    数据转换为excel模板下载
    干货!零售业智能化管理会遇到哪些问题?看懂这篇文章就够了
    YOLOV1详解
    有关flask和装饰器的python学习
    Linux学习-69-Linux系统启动管理
  • 原文地址:https://blog.csdn.net/Apple_wolf/article/details/126207812