gpt4 book ai didi

java - 一些 hibernate 问题

转载 作者:行者123 更新时间:2023-11-29 15:09:36 24 4
gpt4 key购买 nike

我有 2 个问题我想制作具有 utf8 字符集的 Mysql 表,但我不知道应该在哪里设置该设置。(我只有一个 hibernate.cfg.XMl 没有任何用于 hibernate 的 .xml 文件)我不想将 mysql.ini 文件设置为默认设置为 UTF-8 我想将此设置放入 hibernate 状态。

第二个问题:我有这张表:

CREATE TABLE `buildingtel` (
`username` varchar(50) NOT NULL,
`buildingname` varchar(50) NOT NULL,
`tel` varchar(15) NOT NULL,
PRIMARY KEY (`username`,`buildingname`,`tel`),
KEY `FK_buildingtel_2` (`buildingname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

如何将这些映射到 Java 实体我可以这样做:

@Entity
@Table(name = "btel")
public class Btel {

@Id
@GeneratedValue
@Column(name = "id")
private int id;;
@Column(name = "username", length=50)
private String username;
@Column(name = "buildingname", length=50)
private int buildingname;
@Column(name = "tel", length=15)
private int tel;
//some setter & getter
}

但我想将 (username,buildingname,tel) 设置为主键,如何在 hibernate 中通过注释来做到这一点

提前TanX

最佳答案

对于 UTF-8:

<property name=”hibernate.connection.useUnicode”
value=”true” />
<property name=”hibernate.connection.characterEncoding”
value=”UTF-8″ />
<小时/>

至于设置组合主键,这是可能的,但在使用过它之后我可以说我不会推荐它。来自 the documentation :

You can define a composite primary key through several syntaxes:

  • annotate the component property as @Id and make the component class @Embeddable
  • annotate the component property as @EmbeddedId
  • annotate the class as @IdClass and annotate each property of the entity involved in the primary key with @Id

这使得工作变得很痛苦,并且不建议在 Hibernate 中执行此操作。

我建议使用 the @NaturalId annotation :

While not used as identifier property, some (group of) properties represent natural identifier of an entity. This is especially true when the schema uses the recommended approach of using surrogate primary key even if a natural business key exists. Hibernate allows to map such natural properties and reuse them in a Criteria query. The natural identifier is composed of all the properties marked @NaturalId.

关于java - 一些 hibernate 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1149536/

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