Hi. I have the following
Code:
create table users (
user_name varchar(75) not null primary key,
user_pass varchar(75) not null
);
CREATE TABLE `person` (
`personId` int(11) NOT NULL auto_increment,
`name` varchar(75),
`user_name` varchar(75) not null,
PRIMARY KEY (`personId`),
FOREIGN KEY (`user_name`) REFERENCES `users` (`user_name`)
);
Users.java
Code:
package rain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
* Users generated by hbm2java
*/
@Entity
@Table(name = "users", catalog = "dbex91")
public class Users implements java.io.Serializable {
private String userName;
private String userPass;
private Person person;
public Users() {
}
public Users(String userName, String userPass) {
this.userName = userName;
this.userPass = userPass;
}
@Id
@Column(name = "user_name", unique = true, nullable = false, length = 75)
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "user_pass", nullable = false, length = 75)
public String getUserPass() {
return this.userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
@OneToOne(mappedBy="user")
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
Person.java
Code:
package rain;
import javax.persistence.*;
@Entity
@Table(name="PERSON")
public class Person {
private int id;
private Users user;
private String name;
public Person(){
}
public Person(Users user,String name) {
this.user=user;
this.name = name;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="personId")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="user_name")
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
}
DAO code
Code:
Users user = new Users("root","password");
Person person = new Person(user,"vik");
getHibernateTemplate().save(person);
This DAO code gives me the following exception
Code:
Exception in thread "main" org.springframework.dao.DataIntegrityViolationException: could not insert: [rain.Person]; nested exception is org.hibernate.exception.ConstraintViolationException: could not insert: [rain.Person]
Caused by: org.hibernate.exception.ConstraintViolationException: could not insert: [rain.Person]
...
Caused by: java.sql.SQLException: Column 'user_name' cannot be null
When I remove the not null specification from the sql for table person (`user_name` varchar(75)) the insertion happens fine (both person and users tables are populated)???