spring boot联合主键用什么注解
时间: 2023-10-23 17:09:40 浏览: 41
在 Spring Boot 中,联合主键需要使用 `@EmbeddedId` 或 `@IdClass` 注解来标识。如果使用 `@EmbeddedId` 注解,则需要创建一个嵌入式主键类,并在该类上使用 `@Embeddable` 注解。示例代码如下:
```java
@Embeddable
public class MyCompositeKey implements Serializable {
@Column(name = "id1")
private Long id1;
@Column(name = "id2")
private Long id2;
// constructors, getters and setters
}
@Entity
public class MyEntity {
@EmbeddedId
private MyCompositeKey id;
// other fields and methods
}
```
如果使用 `@IdClass` 注解,则需要在实体类中定义一个用于联合主键的类,并在该类上使用 `@IdClass` 注解。示例代码如下:
```java
@IdClass(MyCompositeKey.class)
@Entity
public class MyEntity {
@Id
@Column(name = "id1")
private Long id1;
@Id
@Column(name = "id2")
private Long id2;
// other fields and methods
}
```
需要注意的是,联合主键应该在实体类中定义为一个对象,而不是分别定义多个主键。