Fork me on GitHub

Programming Design Notes

使用 JPA 連接 PostgreSQL

| Comments

首先資料庫內的表格名稱最好為英文小寫,因為 PostgreSQL 會自動將表格名稱轉為小寫。
例子:
INSERT INTO public.User (id, name, password) VALUES (1, 'Lawrence', '123456')

會變成:
INSERT INTO public.user (id, name, password) VALUES (1, 'Lawrence', '123456')

這樣便會找不到表格而出錯。
以下這種寫法才可以順利找到表格。
INSERT INTO public."User" (id, name, password) VALUES (1, 'Lawrence', '123456')

需要將 User 用 " 包起來才可以,而 JPA 中插入資料時,程式最終也會將物件變為 SQL 才能將資料加入或取出。JPA 並不會自動將表格名稱用 " 包起來。

Entity 例子:
package com.blogspot.lawpronotes.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
* The persistent class for the user database table.
*
*/
@Entity
@Table(name = "user", schema = "public")
public class User implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@Column(name = "id")
private Integer id;

@Column(name = "name")
private String name;

@Column(name = "password")
private String password;

public User() {
}

public Integer getId() {
return this.id;
}

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

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return this.password;
}

public void setPassword(String password) {
this.password = password;
}

}

如果表格名稱是大寫又不能改的話,只好將
@Table(name="user", schema="public")
改為
@Table(name="\"User\"", schema="public")

Column 名稱也一樣,將
@Column(name = "name")
改為
@Column(name = "\"Name\"")

相關書籍: PostgreSQL 8.4 Official Documentation - Volume I. The SQL LanguagePostgreSQL 8.4 Official Documentation - Volume II. Server AdministrationPostgreSQL 8.4 Official Documentation - Volume III. Server Programming