//EDIT: Solved! Damn. I justed missed to set up the cascadeType....Now it works. Thank you anyway.
Hello,
I'm totaly frustrated. I have no idea what's wrong. I hope somebody can help me. I am trying to build a simple OneToOne relationship between the tables "address" and "customer". Unfortunately it doesn't work and I got the messages:
10:02:56,129 DEBUG SQL:393 - insert into Customer (address, name) values (?, ?)
Hibernate: insert into Customer (address, name) values (?, ?)
10:02:56,172 WARN JDBCExceptionReporter:77 - SQL Error: 1048, SQLState: 23000
10:02:56,173 ERROR JDBCExceptionReporter:78 - Column 'address' cannot be null
Exception in thread "main" javax.persistence.EntityExistsException: org.hibernate.exception.ConstraintViolationException: could not insert: [com.package.model.Customer]
Here are the classes:
Code:
@Entity
public class Customer {
@Id
@GeneratedValue
private Integer id;
private String name;
@OneToOne
@JoinColumn(name="address")
private Address address;
public Customer(){}
public Customer(String name, Address address){
this.setName(name);
this.setAdresse(address);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Address getAddress() {
return address;
}
public void setAdresse(Address address) {
address.setCustomer(this);
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity
@Table(name="address")
public class Address {
@Id
@GeneratedValue
private Integer id;
private String city;
@OneToOne(mappedBy="address")
private Customer customer;
public Address(){}
public Address(String city) {
this.city = city;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
And this is my TestClass:
Code:
public class CustomerTest {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersManager");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
Customer cust = new Customer("Foo Bar", new Address("N.Y."));
System.out.println(cust.getAddress().getCustomer().getName());
tx.begin();
em.persist(cust);
tx.commit();
em.close();
}
}
I am using MySQL and I set up a foreign key column "address" in the table "customer" to "id" in table "address". May anyone tell me what to do or point me to the error reason? Thanks a lot.
Jonny