我正在尝试遵循JPA 教程并使用ElementCollection
来记录员工电话号码:
PHONE (table)
OWNER_ID TYPE NUMBER
1 home 792-0001
1 work 494-1234
2 work 892-0005
精简版
我需要的是这样的课程:
@Entity
@Table(name="Phones")
public class PhoneId {
@Id
@Column(name="owner_id")
long owner_id;
@Embedded
List<Phone> phones;
}
将每个人的电话号码存储在一个集合中。
长版
我按照教程代码:
@Entity
@Table(name="Phones")
public class PhoneId {
@Id
@Column(name="owner_id")
long owner_id;
@ElementCollection
@CollectionTable(
name="Phones",
joinColumns=@JoinColumn(name="owner_id")
)
List<Phone> phones = new ArrayList<Phone>();
}
@Embeddable
class Phone {
@Column(name="type")
String type = "";
@Column(name="number")
String number = "";
public Phone () {}
public Phone (String type, String number)
{ this.type = type; this.number = number; }
}
稍有不同,我只保留一张桌子。我尝试使用以下代码向该表添加记录:
public static void main (String[] args) {
EntityManagerFactory entityFactory =
Persistence.createEntityManagerFactory("Tutorial");
EntityManager entityManager = entityFactory.createEntityManager();
// Create new entity
entityManager.getTransaction().begin();
Phone ph = new Phone("home", "001-010-0100");
PhoneId phid = new PhoneId();
phid.phones.add(ph);
entityManager.persist(phid);
entityManager.getTransaction().commit();
entityManager.close();
}
但它不断抛出异常
内部异常:org.postgresql.util.PSQLException:错误:“类型”列中的空值违反非空约束详细信息:失败行包含(0,null,null)。错误代码:0 调用:INSERT INTO Phones (owner_id) VALUES (?) bind => [1 parameter bound] 查询:InsertObjectQuery(tutorial.Phone1@162e295)
我做错了什么?