Search code examples
javahibernatespring-mvchibernate-mapping

hibernate - merge parent still getting updated while child returns error


So I have a one to many and many to one relation between two classes. When I try to update an entity, the parent is updated and child throws an error. In that case I expect the parent update to be rolled back but it is not. Since I have a one to many relation, an update on the parent is expected to insert a child but when the child throws an error shouldnt the parent's update be rolled back? If it is of any relation the child's error is thrown due to the unique constraints on the child/account entity.

Below are my two models:

/** User model **/
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", unique = true, nullable = false)
private int id;

@Column(name = "type")
private String type;

@Column(name = "username", nullable = false)
private String username;

...

// define one to many relation between User and Account

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private Set<Account> accounts; 

public User() {
}

@PrePersist
void preInsert() throws ParseException {
    ...
}

// field getters and setters

...

// returns Account list associated with User
public Set<Account> getAccount() { 
    return accounts; 
} 

// set Account list associated with User
public void setAccount(Set<Account> accounts) { 
    this.accounts = accounts; 
}
}

Model 2:

/** Account model **/
@Entity
@Table(name = "account", uniqueConstraints =
@UniqueConstraint(columnNames = {"user_id", "entity_id", "branch_id", "type"}))
public class Account {
private int id;

@Column(name = "user_id", nullable = false)
private int user_id;

...

private User user; 

// constructor
public Account() {

}

@PrePersist
void preInsert() throws ParseException {       
    ...
}

// field getters and setters

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false)
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}

...

// define many to one relation between Account and User

// get User associated with Account

@ManyToOne
@JoinColumn(name = "user_id", insertable = false, updatable = false)
public User getUser() { 
    return user; 
} 

// set User associated with Account
public void setUser(User user) { 
    this.user = user; 
}
}

UserDAO:

@Repository("userDao")
@Transactional(propagation = Propagation.REQUIRED)
public class UserDAO {
@PersistenceContext
private EntityManager entityManager;

public EntityManager getEntityManager() {
    return entityManager;
}

public void setEntityManager(EntityManager entityManager) {
    this.entityManager = entityManager;
}

public void insert(User user) {
    entityManager.persist(user);
}

public void update(User user) {
    entityManager.merge(user);
}
....
}

User service (where i am calling the update)

@Service
public class UserService {
private UserDAO userDAO;

public UserDAO getUserDao() {
    return userDAO;
}

@Autowired
public void setUserDao(UserDAO userDAO) {
    this.userDAO = userDAO;
}

public boolean addUser(SignupComponent signupComponent) {
    ....
    else {
        // case (4)

        // get user object
        User userObj = getUserDao().findUser(user.getPhone());

        // update user object, adding account and account details
        Set<Account> accounts = userObj.getAccount();

        Account a = new Account();
        a.setBranch_id(signupComponent.branch_id);
        a.setEntity_id(signupComponent.entity_id);
        if (signupComponent.type != -1) {
            a.setType(signupComponent.type);
        }
        a.setUser(userObj);

        userObj.setAccount(accounts);
        userObj.setEmail(signupComponent.user.getEmail());

        AccountDetails ad = new AccountDetails(); //never mind this line, i have another one to one relation with another entity
        ad.setAccount(a);

        a.setAccountDetails(ad);

        accounts.add(a);

        try {
            getUserDao().update(userObj);
            return true;
        }
        catch(Exception e) {
            signupComponent.error = e.toString();
            return false;
        }
    }
}
}

Solution

  • You are defining JoinColumn at both the sides.You need to define at one side. How would it store an arbitrary number of foreign keys in a single row? Instead, it must let the tables of the entities in the collection have foreign keys back to the source entity table.

    Try this:

    public class User{    
    
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL,mappedBy="user")
    private Set<Account> accounts; 
    
    }
    

    User class

    /** User model **/
    @Entity
    @Table(name = "user")
    public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", unique = true, nullable = false)
    private int id;
    
    @Column(name = "type")
    private String type;
    
    @Column(name = "username", nullable = false)
    private String username;
    
    ...
    
    // FetchType should be Lazy to improve performance
    
    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL,mappedBy="user")
    private Set<Account> accounts;
    //mappedBy says that this side is inverse side of relation and source is user which is mapped by user field name in Account class
    
    public User() {
    }
    
    @PrePersist
    void preInsert() throws ParseException {
        ...
    }
    
    // field getters and setters
    
    ...
    
    // returns Account list associated with User
    public Set<Account> getAccount() { 
        return accounts; 
    } 
    
    // set Account list associated with User
    public void setAccount(Set<Account> accounts) { 
        this.accounts = accounts; 
    }
    }
    

    Account class

    /** Account model **/

    @Entity
    @Table(name = "account", uniqueConstraints =
    @UniqueConstraint(columnNames = {"user_id", "entity_id", "branch_id", "type"}))
    public class Account {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private int id;
    
    @Column(name = "user_id", nullable = false)
    private int user_id;
    
    ...
    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "user_id", insertable = false, updatable = false)
    private User user; 
    
    // constructor
    public Account() {
    
    }
    
    @PrePersist
    void preInsert() throws ParseException {       
        ...
    }
    
    // field getters and setters
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    
    ...
    
    // define many to one relation between Account and User
    
    // get User associated with Account
    
    
    public User getUser() { 
        return user; 
    } 
    
    // set User associated with Account
    public void setUser(User user) { 
        this.user = user; 
    }
    }
    

    See now, when you save User then Account class will not be updated as User is at inverse side. But when you save Account class then user_id which is present in account table will get update as it is source side of relation.