Issue
I have two entities: Account and Profile. They are connected with an One To One relationship.
Account Entity:
@Entity
@Table(name = "account")
public class Account {
@Id
@Column(name = "account_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne
private Profile profile;
...
}
Profile Enity:
@Entity
@Table(name = "profile")
public class Profile {
@Id
@Column(name = "profile_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(mappedBy = "profile", cascade = CascadeType.ALL)
private Account account;
...
}
The problem is when I try to save in database, a new object from Account and a new object from Profile and connect them. Something like this:
Account account = new Account();
Profile profile = new Profile();
profile.setAccount(account);
account.setProfile(profile);
accountRepository.save(account);
profileRepository.save(profile);
Of course this doesn't work. After searching for a solution I found that I must use persist method and Transactions. However I haven't found how to use them. I tried to use EntityManager and create a persistence.xml
file, but spring doesn't find it (I put it in directory: src/main/resources/Meta-INF).
My question is: Is there a simpler way to save both of the objects (without having to create new xml files etc.)? And if there isn't what exactly do I have to do, in order to make it work?
I use spring with hibernate and mysql, in Netbeans with Maven.
Solution
I finally solved it !
The problem was that the CascadeType.All
property was in the wrong place. It should be in the Account Entity. Also, the profileRepository.save(profile)
is not needed because the cascade of the Account manages the save of the profile. I also had some issues when I tried to show (with JSON) an account, with forever recursion, which I solved thanks to this stackoverflow answer (@JsonManagedReference
and @JsonBackReference
).
So now my code looks like this:
Account Entity:
@Entity
@Table(name = "account")
public class Account {
@Id
@Column(name = "account_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name="profile_id")
@JsonManagedReference
private Profile profile;
...
}
Profile Entity:
@Entity
@Table(name = "profile")
public class Profile {
@Id
@Column(name = "profile_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(mappedBy="profile")
@JsonBackReference
private Account account;
...
}
And for the save in database:
Account account = new Account();
Profile profile = new Profile();
profile.setAccount(account);
account.setProfile(profile);
accountRepository.save(account);
Answered By - Thanasis1101