Reputation: 701
I have two tables in a relationship one to one:
Users:
create table users (
id int not null primary key,
username varchar2(40) not null unique,
password varchar2(60) not null,
firstName varchar2(40) not null,
lastName varchar2(40) not null,
personalId varchar2(11) unique,
city varchar2(40),
address varchar2(40),
email varchar2(40) not null unique,
phone varchar2(9) unique
);
UsersAccounts
create table usersAccounts (
id int primary key,
accountNr varchar2(26) not null unique,
balance float not null,
createDate date not null,
expiredDate date,
lastCharge date,
userId int constraint userAccount_fk_user references users(id),
);
My Entity:
User
@Entity
@Table(name = "users")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@NotBlank
@NotNull
@Size(min = 3, max = 40)
@Column(name = "username")
private String username;
@NotBlank
@NotNull
@Size(min = 3, max = 60)
@Column(name = "password")
private String password;
@NotBlank
@NotNull
@Size(min = 3, max = 40)
@Column(name = "firstName")
private String firstName;
@NotBlank
@NotNull
@Size(min = 3, max = 40)
@Column(name = "lastName")
private String lastName;
@Size(min = 11, max = 11)
@Column(name = "personalId")
private String personalId;
@Size(max = 40)
@Column(name = "city")
private String city;
@Size(max = 40)
@Column(name = "address")
private String address;
@NotBlank
@NotNull
@Email
@Size(max = 40)
@Column(name = "email")
private String email;
@Size(min = 9, max = 9)
@Column(name = "phone")
private String phone;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<UserRole> userRoleSet;
@OneToOne(mappedBy = "user")
private UserAccount userAccount;
UserAccount
@Entity
@Table(name = "usersAccounts")
public class UserAccount implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@NotNull
@Column(name = "accountNr")
private String accountNr;
@NotNull
@Column(name = "balance")
private float balance;
@NotNull
@Column(name = "createDate")
private Date createDate;
@Column(name = "expiredDate")
private Date expiredDate;
@Column(name = "lastCharge")
private Date lastCharge;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "userId")
private User user;
I try persist this, but i have errors:
@RequestMapping(value = "/admin/addAdmin", method = RequestMethod.POST)
public String addAdmin(@ModelAttribute("user") UserDto userDto,
BindingResult result) {
AddUserValidator addUserValidator = new AddUserValidator();
addUserValidator.validate(userDto, result);
if (result.hasErrors()) {
return "admin/addadmin";
} else {
ErrorMessage errorMessage;
User user = prepareModelUser(userDto);
if ((errorMessage = userService.createUser(user)) != null) {
result.rejectValue(errorMessage.getPath(),
errorMessage.getDescription());
return "admin/addadmin";
} else {
user = userService.findByUsername(user.getUsername());
UserRole userRole = new UserRole("ROLE_ADMIN");
userRole.setUser(user);
userRoleService.createUserRole(userRole);
UserAccount ua = new UserAccount();
ua.setAccountNr("12345678901");
ua.setBalance(100);
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String dateStr = dateFormat.format(date);
try {
ua.setCreateDate(dateFormat.parse(dateStr));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
user = userService.findUser(user.getId());
ua.setUser(user);
userAccountService.createUserAccount(ua);
return "redirect:/admin/adminlist";
}
}
}
When i try persist i get this error:
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/ibank] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: pl.piotr.ibank.model.User] with root cause org.hibernate.PersistentObjectException: detached entity passed to persist: pl.piotr.ibank.model.User
userRole.setUser(user);
userRoleService.createUserRole(userRole);
saves good but when i try ua.setUser(user);
userAccountService.createUserAccount(ua);
I get detached entity
Upvotes: 1
Views: 574
Reputation: 24423
It is really bad practice to have your primary key be foreign key at the same time. Especially when you have @GeneratedValue
on it.
On closer look, your entities are mapped ok but usersAccounts
table needs adjusting. Remove that foreign key constraint from id
column, and add new column userId
which will be foreign key to users#id
. Everything should work after that.
Upvotes: 2