gpt4 book ai didi

java - hibernate 创建表时如何排列列?

转载 作者:行者123 更新时间:2023-11-29 13:24:53 25 4
gpt4 key购买 nike

我使用 Hibernate 将 Java 对象映射到 PostgreSQL 数据库。UserDetails 类是用于添加用户的实体类。它包含一个名为 Address 的嵌入对象。

UserDetails.java

@Entity
@Table(name="USER_DETAILS")
public class UserDetails {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="USER_ID")
private int userId;
@Column(name="USER_NAME")
private String userName;
@Temporal(TemporalType.DATE)
@Column(name="JOINED_DATE")
private Date joinedDate;
@Column(name="DESCRIPTION")
private String description;
@Embedded
private Address address;
}

地址对象包含有关地址的详细信息,如城市、密码、街道和州。

地址.java

import javax.persistence.Embeddable;

@Embeddable
public class Address {
private String street;
private String city;
private String state;
private String pincode;
}

包含main方法的类如下:

public class HibernateTest {
public static void main(String[] args){
UserDetails user = new UserDetails();
UserDetails user1 = new UserDetails();

user.setUserName("First User");

Address newAddress = new Address();
newAddress.setCity("Pune");
newAddress.setPincode("411057");
newAddress.setState("Maharashtra");
newAddress.setStreet("Hinjewadi");

user.setAddress(newAddress);
user.setDescription("just like that");
user.setJoinedDate(new Date());
user1.setUserName("Second User");
user1.setDescription("great here");
user1.setJoinedDate(new Date());

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.save(user1);
session.getTransaction().commit();
session.close();

user = null;

session = sessionFactory.openSession();
session.beginTransaction();
user = session.get(UserDetails.class, 1);
System.out.println(user.getUserName());
session.close();
sessionFactory.close();
}
}

生成的 SQL 查询如下所示,这表明列的添加顺序与它们声明的顺序不同。

Hibernate: create sequence hibernate_sequence start 1 increment 1
Hibernate: create table USER_DETAILS (USER_ID int4 not null, city varchar(255), pincode varchar(255), state varchar(255), street varchar(255), DESCRIPTION varchar(255), JOINED_DATE date, USER_NAME varchar(255), primary key (USER_ID))

在hibernate中添加列有什么规定吗?

最佳答案

hbm to ddl library 使用反射来获取类中的字段,根据文档,字段的顺序不被保留/保证:

https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getFields()

Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object. The elements in the array returned are not sorted and are not in any particular order. This method returns an array of length 0 if the class or interface has no accessible public fields, or if it represents an array class, a primitive type, or void.

在编写依赖于反射的库时,我遇到过类似的问题。

关于java - hibernate 创建表时如何排列列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35634244/

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