#OneToMany mapped by doesn't make an entry to the table - spring

Here I have two entity class. I used OneToMany and ManyToOne mapping.
#Entity
#Table(name="test_user")
public class TestUser {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer user_id;
private String user_name;
#OneToMany(mappedBy = "testuser", fetch=FetchType.EAGER, cascade = CascadeType.ALL)
private Set<UserAnswer> answer = new HashSet<UserAnswer>();
public Set<UserAnswer> getAnswer() {
return answer;
}
public void setAnswer(Set<UserAnswer> answer) {
this.answer = answer;
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
}
This is my second entity class
#Entity
#Table(name="user_answer")
public class UserAnswer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer answer_id;
private String answer;
#ManyToOne
#JoinColumn(name="user_id")
private TestUser testuser;
public TestUser getTestuser() {
return testuser;
}
public void setTestuser(TestUser testuser) {
this.testuser = testuser;
}
public Integer getAnswer_id() {
return answer_id;
}
public void setAnswer_id(Integer answer_id) {
this.answer_id = answer_id;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
When I insert user and answer, user_id is not getting stored in user_answer table.
Here is my JSON input format.
{
"user_name":"myname",
"answer":[
{
"answer":"myanswer"
}
]
}
When I fetch the data I am getting JSON response like this,
[
{
"user_id": 52,
"user_name": "myname",
"answer": []
}
]
Here is my service code snippet,
#Autowired
private TestUserRepository repo;
#Override
public TestUser addUser(TestUser user) {
return repo.save(user);
}
Here is my controller code snippet
#Autowired
private TestUserApiService service;
#RequestMapping(value = "/saveuser", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.POST)
public ResponseEntity<TestUser> addUser(#RequestBody TestUser user)
throws NotFoundException {
return new ResponseEntity<TestUser>(service.addUser(user),
HttpStatus.OK);
}

The relation you have here is bidirectional, which means each side of the relation should have a reference to the other side.
Your input format has TestUser which has a UserAnswer set since you are cascading your UserAnswer inside your TestUser you would expect to persist the relation, but your UserAnswer should have a reference to TestUser as well to complete the relations.
you can do two things, first you can make your relation unidirectional, or you can extract the coming UserAnswer and inject the TestUser to them then persist the TestUser

Related

How to load a full graph of 2 entities that are in relationship #OneToMany each other with a Join Table

I'm using Spring Boot and Spring Data and I have a problem when trying to load entities using JPA and EntityGraph.
I have a Patient and Insurance entities. Each Patient can have many Insurances and each Insurance can be assigned to many patients. I decided to use a Join Table PatientInsurance because I need to store extra fields like 'active', and also the relation code (a Patient can be a Member, Spouse, or Child for that specific insurance).
Using Spring Data repositories I annotated the method to find a patient, with an EntityGraph, to have ready the list of PatientInsurances (and Insurances) for that patient in one query.
This is the code (I removed the non-necessary parts in the scope)
Patient class
#Entity
#Table(name = "patient")
public class Patient {
#NotNull
#NotEmpty
#Column(length = 60, nullable = false)
private String patientFirstName;
#NotNull
#NotEmpty
#Column(length = 60, nullable = false)
private String patientLastName;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patient", cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
List<PatientInsurance> patientsInsurances = new ArrayList<>();
public void addPatientInsurance(PatientInsurance patientIns) {
if (!patientsInsurances.contains(patientIns)) {
patientsInsurances.add(patientIns);
}
}
//other properties...
Insurance class
#Entity
#Table(name = "insurance")
public class Insurance {
#Column(name = "policy_id", length = 20)
private String policyId;
#OneToMany(mappedBy = "insurance", fetch = FetchType.LAZY,cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
private List<PatientInsurance> patientsInsurances = new ArrayList<PatientInsurance>();
public void addPatientInsurance(PatientInsurance patientIns) {
if (!patientsInsurances.contains(patientIns)) {
patientsInsurances.add(patientIns);
}
}
//other properties
Entity for the join table between patient and insurance (needed a join table for extra field in this entity like active and relCode
#Entity
#IdClass(PatientInsurance.PatientInsurancePK.class)
#Table(name = "patient_insurance")
public class PatientInsurance implements Serializable {
#Id
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "patient_id")
private Patient patient;
#Id
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "insurance_id")
private Insurance insurance;
#Column(name = "active")
private boolean active;
#Column(length = 1)
private String relCode;
public PatientInsurance() {
insurance = new Insurance();
patient = new Patient();
}
public PatientInsurance(Patient p, Insurance i, boolean active, String relCode) {
this.patient = p;
this.insurance = i;
this.active = active;
this.relCode = relCode;
p.addPatientInsurance(this);
i.addPatientInsurance(this);
}
public Patient getPatient() {
return patient;
}
public Insurance getInsurance() {
return insurance;
}
public void setInsurance(Insurance insurance) {
this.insurance = insurance;
insurance.addPatientInsurance(this);
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public void setPatient(Patient patient) {
this.patient = patient;
patient.addPatientInsurance(this);
}
public String getRelCode() {
return relCode;
}
public void setRelCode(String relCode) {
this.relCode = relCode;
}
static public class PatientInsurancePK implements Serializable {
protected Patient patient;
protected Insurance insurance;
public PatientInsurancePK() {
}
public PatientInsurancePK(Patient patient, Insurance insurance) {
this.patient = patient;
this.insurance = insurance;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PatientInsurancePK)) return false;
PatientInsurancePK that = (PatientInsurancePK) o;
if (!patient.equals(that.patient)) return false;
return insurance.equals(that.insurance);
}
#Override
public int hashCode() {
int result = (patient != null) ? patient.hashCode() : 0;
result = 31 * result + ((insurance != null) ? insurance.hashCode() : 0);
return result;
}
}
}
Implementation of the PatientService
#Transactional
#Service("patientService")
public class PatientServiceImpl implements PatientService {
#Autowired
PatientRepository patientRepository;
#Override
public Optional<Patient> findByIdFull(Long id) {
Optional<Patient> patient = patientRepository.findById(id);
return patient;
}
//other methods...
Patient Repository
public interface PatientRepository extends JpaRepository<Patient, Long> {
#EntityGraph(
attributePaths = {
"patientsInsurances",
"patientsInsurances.patient",
"patientsInsurances.insurance"},
type = EntityGraph.EntityGraphType.LOAD)
Optional<Patient> findById(Long id);
A snippet of code that calls the method in PatientService
Optional<Patient> patientOptional = patientService.findByIdFull(p.getId());
if (patientOptional.isPresent()) {
Patient patient1 = patientOptional.get();
List<PatientInsurance> patientInsurances = patient1.getPatientInsurances();
PatientInsurances patientInsurance = patientInsurances.get(0);
Patient patient2 = patientInsurance.getPatient(); //and this is same istance of patient1, it's ok
Insurance insurance = patientInsurance.getInsurance();
//here is the problem!!!
insurance.getPatientInsurances();
//Unable to evaluate the expression Method threw 'org.hibernate.LazyInitializationException' exception.
So the problem seems that when I go inside the patient side, I can loop into his Insurances without problems, but when I try to do the same starting from the Insurance instance, I cannot loop into its patients cause they are lazily loaded.
So how to make jpa download the full graph in the correct way?

Many to One Relationship returns NULL List of Child Object

I have 2 classes. USER class & ORDER class.
Order class has User object with #ManyToOne relationship.
When the RestController retrieves the Order object post insertion of Order object using #PostMapping,it returns null value for nested User object
Rest Controller
#RestController
public class OrderController {
#PersistenceContext
EntityManager entityManager;
#Transactional
#PostMapping(value = "api/v1/create/order")
public Order createOrder(#RequestBody Order order){
entityManager.persist(order);
return order;
}
}
Order class
#Entity
#Table(name = "booking_order")
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Integer orderID;
#Column
String transactionAmount;
#Column
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
Date bookingTimestamp;
#ManyToOne
User user;
public Order(){}
public Integer getOrderID() {
return orderID;
}
public void setOrderID(Integer orderID) {
this.orderID = orderID;
}
public String getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(String transactionAmount) {
this.transactionAmount = transactionAmount;
}
public Date getBookingTimestamp() {
return bookingTimestamp;
}
public void setBookingTimestamp(Date bookingTimestamp) {
this.bookingTimestamp = bookingTimestamp;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
User Class
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
#Column(unique = true)
String username;
#Column
String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Input JSON
{
"transactionAmount" : "100.50",
"user":{
"id":1
}
}
Order Response
{
"orderID": 1,
"transactionAmount": "100.50",
"bookingTimestamp": "2019-05-15T20:44:43.234+0000",
"user": {
"id": 1,
"username": null,
"password": null
}
}

Hibernate transaction and session with multiple save

Thanks, let me completely change it.
Using:
Spring Boot, Hibernate JPA
I have created a link table with a composite primary key across all 3 columns(event_attendee_link_program)
I used the JPA tools in STS IDE to generate Entities from my tables and it came up with the below code. I removed some of the columns to save space.
EventAttendee.java
#Entity
#Table(name="event_attendee")
#NamedQuery(name="EventAttendee.findAll", query="SELECT e FROM EventAttendee e")
public class EventAttendee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="attendee_id")
private long attendeeId;
//bi-directional many-to-one association to EventAttendeeLinkProgram
#OneToMany(mappedBy="eventAttendee")
private List<EventAttendeeLinkProgram> eventAttendeeLinkPrograms;
public List<EventAttendeeLinkProgram> getEventAttendeeLinkPrograms() {
return this.eventAttendeeLinkPrograms;
}
public void setEventAttendeeLinkPrograms(List<EventAttendeeLinkProgram> eventAttendeeLinkPrograms) {
this.eventAttendeeLinkPrograms = eventAttendeeLinkPrograms;
}
public EventAttendeeLinkProgram addEventAttendeeLinkProgram(EventAttendeeLinkProgram eventAttendeeLinkProgram) {
getEventAttendeeLinkPrograms().add(eventAttendeeLinkProgram);
eventAttendeeLinkProgram.setEventAttendee(this);
return eventAttendeeLinkProgram;
}
public EventAttendeeLinkProgram removeEventAttendeeLinkProgram(EventAttendeeLinkProgram eventAttendeeLinkProgram) {
getEventAttendeeLinkPrograms().remove(eventAttendeeLinkProgram);
eventAttendeeLinkProgram.setEventAttendee(null);
return eventAttendeeLinkProgram;
}
}
EventAttendeeLinkProgram.java
#Entity
#Table(name="event_attendee_link_program")
#NamedQuery(name="EventAttendeeLinkProgram.findAll", query="SELECT e FROM EventAttendeeLinkProgram e")
public class EventAttendeeLinkProgram implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private EventAttendeeLinkProgramPK id;
//bi-directional many-to-one association to EventAttendee
#ManyToOne
#JoinColumn(name="attendee_id", insertable=false, updatable=false)
private EventAttendee eventAttendee;
//bi-directional many-to-one association to EventOptionsAttendeeType
#ManyToOne
#JoinColumn(name="attendee_type_id", insertable=false, updatable=false)
private EventOptionsAttendeeType eventOptionsAttendeeType;
//bi-directional many-to-one association to EventProgram
#ManyToOne
#JoinColumn(name="program_id", insertable=false, updatable=false)
private EventProgram eventProgram;
public EventAttendeeLinkProgram() {
}
public EventAttendeeLinkProgramPK getId() {
return this.id;
}
public void setId(EventAttendeeLinkProgramPK id) {
this.id = id;
}
public EventAttendee getEventAttendee() {
return this.eventAttendee;
}
public void setEventAttendee(EventAttendee eventAttendee) {
this.eventAttendee = eventAttendee;
}
public EventOptionsAttendeeType getEventOptionsAttendeeType() {
return this.eventOptionsAttendeeType;
}
public void setEventOptionsAttendeeType(EventOptionsAttendeeType eventOptionsAttendeeType) {
this.eventOptionsAttendeeType = eventOptionsAttendeeType;
}
public EventProgram getEventProgram() {
return this.eventProgram;
}
public void setEventProgram(EventProgram eventProgram) {
this.eventProgram = eventProgram;
}
}
EventAttendeeLinkProgramPK.java
#Embeddable
public class EventAttendeeLinkProgramPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name="attendee_id", insertable=false, updatable=false)
private int attendeeId;
#Column(name="attendee_type_id", insertable=false, updatable=false)
private int attendeeTypeId;
#Column(name="program_id", insertable=false, updatable=false)
private int programId;
public EventAttendeeLinkProgramPK() {
}
public int getAttendeeId() {
return this.attendeeId;
}
public void setAttendeeId(int attendeeId) {
this.attendeeId = attendeeId;
}
public int getAttendeeTypeId() {
return this.attendeeTypeId;
}
public void setAttendeeTypeId(int attendeeTypeId) {
this.attendeeTypeId = attendeeTypeId;
}
public int getProgramId() {
return this.programId;
}
public void setProgramId(int programId) {
this.programId = programId;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof EventAttendeeLinkProgramPK)) {
return false;
}
EventAttendeeLinkProgramPK castOther = (EventAttendeeLinkProgramPK)other;
return
(this.attendeeId == castOther.attendeeId)
&& (this.attendeeTypeId == castOther.attendeeTypeId)
&& (this.programId == castOther.programId);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.attendeeId;
hash = hash * prime + this.attendeeTypeId;
hash = hash * prime + this.programId;
return hash;
}
}
EventAttendeeServiceImpl.java
#Service
#Primary
public class EventAttendeeServiceImpl implements EventAttendeeService {
#Autowired
private EventAttendeeRepository eventAttendeeRepository;
#Autowired
private EventOptionsAttendeeTypeRepository eventOptionsAttendeeTypeRepository;
#Autowired
private EventProgramRepository eventProgramRepository;
#Override
#Transactional
public String addEventAttendee(EventAttendee eventAttendee) {
EventAttendeeLinkProgram ep = new EventAttendeeLinkProgram();
ep.setEventOptionsAttendeeType(eventOptionsAttendeeTypeRepository.findOne(2L));
ep.setEventProgram(eventProgramRepository.findOne(2L));
eventAttendee.setEventAttendeeLinkPrograms(new ArrayList<>());
eventAttendee.getEventAttendeeLinkPrograms().add(ep);
eventAttendeeRepository.save(eventAttendee);
return "";
}
With this in place, my code is not throwing any errors. It is saving the EventAttendee, but nothing is being saved to the EventAttendeeLinkProgram. Please Note: I am trying so save both EventAttendee and EventAttendeeLinkProgram entities. So I think hibernate should be smart enought to forst save EventAttendee and generating the Id for it, then use that Id to store in EventAttendeeLinkProgram.
Why don't you let spring do the heavy lifting:
First create a JPA repository in spring:
public interface UserRepository extends CrudRepository<User, Long>{
}
Then create your 2 entities with the relationship
#Entity
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true, fetch = FetchType.EAGER)
private List<UserType> userTypes;
And :
#Entity
public class UserType {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "user_id")
private User user;
My test looks like this:
#RunWith(SpringRunner.class)
#SpringBootTest(classes = Application.class)
public class UserRepositoryTest extends AbstractTest {
#Autowired
private UserRepository userRepository;
#Test
#Transactional
public void test1() throws SQLException {
showTables();
User user1 = makeUser("Greg");
userRepository.save(user1);
System.out.println(user1);
userRepository.save(makeUser("George"));
assertEquals(2, userRepository.count());
User user = userRepository.findOne(1l);
}
User makeUser(String name) {
User user = new User();
user.setName(name);
user.setUserTypes(new ArrayList<>());
user.getUserTypes().add(makeUserType("admin"));
user.getUserTypes().add(makeUserType("head chef"));
return user;
}
UserType makeUserType(String description) {
UserType userType = new UserType();
userType.setDescription(description);
return userType;
}
}
First of all, user save return the identifier directly
Long insertId = (Long) session.save(user);
Then you'd better call the rollback on the txtransaction itself instead of retrieving again the transaction from the session.
Finally, when using spring you should consider to let spring manage the transaction itself (container managed transaction)using #Transactional annotation instead of using user managed transaction. It's logical as you let spring manage the session for you (sessionFactory.getCurrentSession()) and both session and transaction should have the same scope (e.g. the unit of work).
Consider reading some literature on Session (e.g. JPA entityManager) and transaction management.

Get Join Table Data using Hibernate

I have two tables and trying to get data with inner join using hibernate with spring.
And i will get json using ModelMapper and get duplicate record also.
So, please suggest me how to get unique record with inner join query using hibernate.
I have Two Tables:
Table Name: User
---------------------
id | email
---------------------
1 | m#gmail.com
2 | e#gmail.com
---------------------
Table Name: Userrole
----------------------------------------
roleid | userid | rolename
----------------------------------------
1 | 1 | Admin
2 | 1 | HR
3 | 2 | Employee
4 | 2 | Executive
----------------------------------------
#Entity
#Table(name="user")
public class User{
#Id
#GeneratedValue
private int id;
#Column
private String email;
#OneToMany
private List<Userrole> userroles;
public void setId(int id){
this.id = id;
}
public void setEmail(String email){
this.email= email;
}
public int getId(){
return id;
}
public String getEmail(){
return email;
}
public List<Userrole> getUserrole(){
return userroles;
}
}
#Entity
#Table(name="userrole")
public classs Userrole{
#Id
#GeneratorValue
private int roleid;
#Column
private String rolename;
#ManyToOne
private User user;
// setter and getter
}
public List<User> findAall(){
// Type casting will throw an error
// This will throw error
return (List<User>)session.getCurrentSession().createQuery("from User u join u.userroles");
// this will return List<Object[]>
return session.getCurrentSession().createQuery("from User u join u.userroles");
// So i want to convert to this DTO using ModelMapper object
}
public class UserDTO{
private int id;
private String email;
private List<Userrole> roleusers;
// setter and getter
}
public class UserroleDTO{
private int roleid;
private String rolename;
//settter and getter
}
public interface UserDao{
public List<User> findAll();
}
#Repository
public class UserDaoImpl implements UserDao{
#Override
public List<User> findAll(){
// This will throw an error: ClassCastException
return (List<User>)session.getCurrentSession().createQuery("from User u join u.userroles");
// This will work perfectly and return List<Object[]>
return session.getCurrentSession().createQuery("from User u join u.userroles");
}
}
#Controller
public class HomeController{
#Autowired
private UserDao doa;
ModelMapper modelMapper = new ModelMapper();
#RequestMapping(value="/list")
public List<User> findAll(){
List<User> list = dao.findAll();
List<UserDTO> dto = list.stream().map(user -> convertToDto(user)).collect(Collectors.toList());
return dto;
// This will return
[
{
"id":1,
"email":"m#gmail.com",
"userroles":[
{
"roleid":1,
"rolename":"Admin"
},
{
"roleid":2,
"rolename":"HR"
}
]
},
{
"id":1,
"email":"m#gmail.com",
"userroles":[
{
"roleid":1,
"rolename":"Admin"
},
{
"roleid":2,
"rolename":"HR"
}
]
},
{
"id":2,
"email":"e#gmail.com",
"userroles":[
{
"roleid":3,
"rolename":"Employee"
},
{
"roleid":4,
"rolename":"Executive"
}
]
},
{
"id":2,
"email":"e#gmail.com",
"userroles":[
{
"roleid":3,
"rolename":"Employee"
},
{
"roleid":4,
"rolename":"Executive"
}
]
}
]
// It should return
[
{
"id":1,
"email":"m#gmail.com",
"userroles":[
{
"roleid":1,
"rolename":"Admin"
},
{
"roleid":2,
"rolename":"HR"
}
]
},
{
"id":2,
"email":"e#gmail.com",
"userroles":[
{
"roleid":3,
"rolename":"Employee"
},
{
"roleid":4,
"rolename":"Executive"
}
]
}
]
}
public UserDTO convertToDto(User user){
UserDTO dto = modelMapper.map(user,UserDTO.class);
return dto;
}
}

Creating a node in neo4j with one unique property other than ID

My Project is based on Spring boot + Neo4j .
I am trying to create a new Privilege node , but don't want to duplicate Privilege.
Now I have a UserRole node which is holds List<Privilege>. Now
I want that when I create a Privilege , it check first is another Privilege exists with same privilegeName property.
Below are my domain classes.
UserRole Class
#NodeEntity
public class UserRole {
public UserRole(User user, Role role) {
this.user = user;
this.role = role;
}
/**
For Jackson Parsing
**/
public UserRole() {
}
#GraphId
private Long id;
public UserRole(User user, Role role, Unit unit) {
this.user = user;
this.role = role;
this.unit = unit;
}
public long getId() {
return id;
}
#Relationship(type = HAS_USERROLE,direction = "OUTGOING")
User user;
public User getUser() {
return user;
}
#Relationship (type = HAS_ROLE_OF,direction = "OUTGOING")
Role role;
public Role getRole() {
return role;
}
#Relationship(type = "WORKS_IN",direction = "OUTGOING")
Unit unit;
public Unit getUnit() {
return unit;
}
public void setUnit(Unit unit) {
this.unit = unit;
}
#Relationship(type = "HAS_PRIVILEDGE", direction = "OUTGOING")
List<Priviledge> priviledgeList;
public List<Priviledge> getPriviledgeList() {
return priviledgeList;
}
public void setPriviledgeList(List<Priviledge> priviledgeList) {
this.priviledgeList = priviledgeList;
}
}
Privilege Class
#GraphId
Long id;
private String priviledge;
private String priviledgeOn;
private Long priviledgeOnId;
public Priviledge() {
}
public Priviledge(String priviledge, String priviledgeOn) {
this.priviledge = priviledge;
this.priviledgeOn = priviledgeOn;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPriviledge() {
return priviledge;
}
public void setPriviledge(String priviledge) {
this.priviledge = priviledge;
}
public String getPriviledgeOn() {
return priviledgeOn;
}
public void setPriviledgeOn(String priviledgeOn) {
this.priviledgeOn = priviledgeOn;
}
public Long getPriviledgeOnId() {
return priviledgeOnId;
}
public void setPriviledgeOnId(Long priviledgeOnId) {
this.priviledgeOnId = priviledgeOnId;
}
}
I am Using GraphRepository to save Entities.
The only way to do this currently is to query for the Privilege existing first and then create it if not, or use it if it does. Also add a unique constraint to be safe.
In a future release, this use case will be supported.

Resources