Java实体类设置联合主键_javahibernate使用注解来定义联合主键

本文详细介绍了如何使用Hibernate的注解定义联合主键,包括将组件类注解为@Embeddable,使用@EmbeddedId,以及使用@IdClass。通过三种方式展示了在Java实体类中设置联合主键的具体代码实现。
摘要由CSDN通过智能技术生成

java hibernate使用注解来定义联合主键

下面使用hibernate的API中说明的三种方式来定义主键,主要使用Annotation来定义hibernate中的联合主键

下面取至hibernate的API文档:

定义组合主键的几种语法:

1、将组件类注解为@Embeddable,并将组件的属性注解为@Id

2、将组件的属性注解为@EmbeddedId

3、将类注解为@IdClass,并将该实体中所有属于主键的属性都注解为@Id

下面就分别使用这三种方式来定义联合主键。

建表的SQL语句:

CREATE TABLE `syslogs` (

`id` varchar(50) NOT NULL,

`yhid` varchar(50) NOT NULL,

`modelname` varchar(100) DEFAULT NULL,

`content` varchar(500) DEFAULT NULL,

`inserttime` varchar(20) DEFAULT NULL,

`remark` varchar(50) DEFAULT NULL,

PRIMARY KEY (`id`,`yhid`)

) ENGINE=InnoDB DEFAULT CHARSET=utf-8;

一、将组件类注解为@Embeddable

/**

* SysLogsDtoId代表主键类

*/

package com.hibernate.dto;

import javax.persistence.Embeddable;

/**

* 1、主键类必须要实现java.io.Serializable接口

* 2、主键类必须要重写equals和hashCode方法

* @author ibm

*/

@Embeddable

public class SysLogsDtoId implements java.io.Serializable {

private static final long serialVersionUID = 1L;

private String id;

private String yhid;

public SysLogsDtoId() {

}

public SysLogsDtoId(String id, String yhid) {

this.id = id;

this.yhid = yhid;

}

public String getId() {

return this.id;

}

public void setId(String id) {

this.id = id;

}

public String getYhid() {

return this.yhid;

}

public void setYhid(String yhid) {

this.yhid = yhid;

}

public boolean equals(Object other) {

if ((this == other))

return true;

if ((other == null))

return false;

if (!(other instanceof SysLogsDtoId))

return false;

SysLogsDtoId castOther = (SysLogsDtoId) other;

return ((this.getId() == castOther.getId()) || (this.getId() != null && castOther.getId() != null && this.getId().equals(castOther.getId())))

&& ((this.getYhid() == castOther.getYhid()) || (this.getYhid() != null && castOther.getYhid() != null && this.getYhid().equals(

castOther.getYhid())));

}

public int hashCode() {

int result = 17;

result = 37 * result + (getId() == null ? 0 : this.getId()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值