-1

我在 PostgreSQL 数据库中使用休眠创建两个关联表时遇到问题。我倾向于认为问题在于数据库(配置?),因为我已经尝试了 Internet 站点中提出的几乎所有 Hibernate 方法,但仍然收到相同的错误。使用 PostgreSql 数据库之前是否需要任何配置?我无法以其他方式解释出现的错误:

“关系部门不存在”

我加入两个实体员工和部门如下:

@Entity
@Table(name="EMPLOYEE")
public class Employee implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="employee_id")
private Long employeeId;
.
.
.

@ManyToOne
@JoinColumn(name="department_id")
public Department getDepartment() {
    return department;
}

public void setDepartment(Department department) {
    this.department = department;
}

private Department department; 

@Entity
@Table(name="DEPARTMENT")
public class Department implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="DEPARTMENT_ID")
private Long departmentId;

.
.
.
@OneToMany(mappedBy="department")
public Set<Employee> getEmployees() {
    return employees;
}

public void setEmployees(Set<Employee> employees) {
    this.employees = employees;
}


private Set<Employee> employees;

我正在尝试在主要方法中创建带有几条记录的表:

SessionFactory sf = new Configuration().configure().buildSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();

        Department department = new Department();
        department.setDepartmentName("Sales");
        session.persist(department);

        Employee emp1 = new Employee("Nina", "Mayers", "111");
        Employee emp2 = new Employee("Tony", "Almeida", "222");

        emp1.setDepartment(department);
        emp2.setDepartment(department);

        session.persist(emp1);
        session.persist(emp2);

        session.getTransaction().commit();
        session.close();

错误出现在行上:session.persist(department);

是否有人在 PostgreSql 数据库方面有经验,可以帮助我找出为什么它无法识别表/关系并出现错误:

“关系部不存在”?

更新:

我查看了日志文件。在 Eclipse 发出通常的消息之后,消息的最后一行是:“无法建立连接,因为目标机器主动拒绝了它”。我推断问题可能出在连接上。是否有任何属性,我应该设置(在 pgAdmin 中)以实现连接?我已经设置了线路

<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/testDB</property>在 Eclipse 的 cfg.xml 文件中。

4

2 回答 2

1

Start psql your_database and issue \d to see the tables.

I'm unfamiliar with Hibernate, but chances are that statements such as @Table(name="DEPARTMENT") are creating tables that are actually called "DEPARTMENT", while your queries are actually querying from DEPARTMENT (without the double quotes), which postgresql will interpret as department.

If so, the fix is to either use lowercase for your table names when creating them, or to make Hibernate use double-quotes and caps when querying your tables.

于 2013-04-27T10:26:39.193 回答
0

如果您也有连接问题,那么解决这些问题的过程就是您所期望的。

  1. 检查 postgreSQL 服务器是否正在运行
  2. 检查您是否可以通过 psql/pgAdmin 连接
  3. 检查您的应用程序中的连接设置是否与您在步骤 2 中使用的相同
  4. 检查连接调用的返回码
  5. 在 PostgreSQL 中打开连接日志并查看您是否收到 (a) 尝试和 (b) 错误
  6. 简化代码以找出错误所在。

令人惊讶的时间#1 或#3 是原因,大概你没有做#4 或者你不会打扰询问其他错误。

于 2013-04-27T06:15:47.237 回答