gpt4 book ai didi

java - 保存实体对象时 Hibernate 复合主键问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:57:52 27 4
gpt4 key购买 nike

我正在尝试使用 hibernate 保存实体,但不知何故无法在数据库表中看到记录,没有生成异常。

我的表、类和hbm.xml文件映射如下。

表:表具有复合主键作为 id 和移动列。

CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
`mobile` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`name` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
PRIMARY KEY (`id`,`mobile`)
);

类(class):

public class StudentPk implements Serializable {
private Integer id;
private String mobile;

public StudentPk() {
super();
}

public StudentPk(Integer id, String mobile) {
super();
this.id = id;
this.mobile = mobile;
}


public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getMobile() {
return mobile;
}

public void setMobile(String mobile) {
this.mobile = mobile;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((mobile == null) ? 0 : mobile.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StudentPk other = (StudentPk) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (mobile == null) {
if (other.mobile != null)
return false;
} else if (!mobile.equals(other.mobile))
return false;
return true;
}


}


class Student{
private StudentPk pk;
private String name;

--getter-setter-

}

hibernate 映射:

<class name="com.Student" table="student" proxy="com.Student">
<composite-id name="id" class="com.StudentPk" >
<key-property name="id" type="java.lang.Integer" column ="id"/>
<key-property name="mobile" type="string" column ="mobile" />
</composite-id>
<property name="name" column="name" type="string" />
</class>

我也在 hibernate.cfg.xml 文件中映射了这个 hbm.xml 文件。

请帮助我。

最佳答案

编写主键类时必须牢记的几条规则:

  1. 主键类必须是公共(public)的,并且必须有一个公共(public)的无参数构造函数。
  2. 主键类必须是可序列化的。
  3. 主键类必须定义equals和hashCode方法。

关于java - 保存实体对象时 Hibernate 复合主键问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32240923/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com