Java EE 6을 사용하고 있습니다. 먼저 꺼내고 싶습니다.
여기에 관계가 있습니다. customer
는 할 수 facility
여러 여기에 여기에 고객 클래스지속성과 일대일 관계
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="CUSTOMER_FK", nullable=false)
private List<Facility> facilities;
public Customer(){
facilities = new ArrayList<Facility>();
}
public Customer(Long id, String name, List<Facility> facilities) {
this.id = id;
this.name = name;
this.facilities = facilities;
}
//set and get method
...
public void addFacility(Facility facility){
this.facilities.add(facility);
}
}
입니다 시설 이제 주요 클래스
@Entity
public class Facility {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Facility(){}
public Facility(Long id, String name, Address address, List<Project> project) {
this.id = id;
this.name = name;
}
//Set and get method
...
}
난 그냥이있는 경우, 그것은 잘 작동합니다. 나는이 최대한 빨리 시설을 추가하고 FK의 구속을 강제로 시도로, 그러나 내 데이터베이스
Customer customer = new Customer();
customer.setName("Wake Forest University");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("EntityLibraryPU");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(customer);
tx.commit();
에 삽입 얻을 볼 수 있습니다. 일이 깨기 시작합니다.
Customer customer = new Customer();
customer.setName("Wake Forest University");
Facility facility = new Facility();
facility.setName("Xia");
customer.addFacility(facility);
EntityManagerFactory emf = Persistence.createEntityManagerFactory("EntityLibraryPU");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(customer);
tx.commit();
여기에 오류가 있습니다. 먼저 동일한 Wake Forest University 고객의 고객 기록을 고객 테이블에 삽입합니다 (name
속성이 고유하지 않음, 데이터베이스에 한 번에 두 개의 항목이 삽입 됨). 그러나 아무것도 내 FACILITY 테이블에 삽입되지 않습니다. 왜 그런가? 오류 코드 중 하나는 Field 'customer_fk' doesn't have a default value
입니다. 어쩌면 그것은 당신에게 조금 암시 할 수 있습니다. 나는 모른다. 나는 오류 로그에 볼 때 : Call: INSERT INTO FACILITY (ID, NAME, STREET2, STREET1, ZIPCODE, STATE, CITY, COUNTRY) VALUES (?, ?, ?, ?, ?, ?, ?, ?)bind => [2, Xia, null, null, null, null, null, null]
, 내 FACILITY
테이블은 내가 CUSTOMER
과 FACILITY
사이에 일대 다 관계를 강제하려고 할 때 생성되는 필드 CUSTOMER_FK
을 가지고 있지만 쿼리는 해당 필드에 아무것도 삽입하지 마십시오
부수적으로, 당신은'시설 '에'equals'과'hashCode'를 구현해야합니다. –
분명히 양방향 관계 여야합니다. 고마워 문제 해결. 도와 줘서 고마워. 모두들. 단방향에 대한 언급이 나에게 많은 도움이되기 때문에 파스칼에게 감사드립니다. 고마워요 –