1

I have 3 @Entity classes mapped to 3 tables in my database. The entity classes are

@Entity
@Table( name = "gbi_user" )
public class UserModel {

@Id
@GeneratedValue( strategy = GenerationType.AUTO )
@Column( name = "u_id" )
private Long id;

@Column( name = "u_fname" )
private String firstName;

@Column( name = "u_lname" )
private String lastName;

//getters and setters

}

@Entity
@Table( name = "gbi_reachable_address" )
public class AddressModel {

@Id
@GeneratedValue( strategy = GenerationType.AUTO )
@Column( name = "ra_id" )
private Long id;

 @Column( name = "ra_city" )
private String city;
 @Column( name = "ra_zip" )
private Integer zip;

// getters and setters
}

@Entity
@Table( name = "gbi_user_to_address" )
public class UserToAddress {

@Id
@GeneratedValue( strategy = GenerationType.AUTO )
@Column( name = "uta_id" )
private Long id;

@ManyToOne( fetch = FetchType.EAGER )
@JoinColumn( name = "uta_frn_user_id", referencedColumnName = "u_id" )
private UserModel user;

@ManyToOne( fetch = FetchType.EAGER )
@JoinColumn( name = "uta_frn_add_id", referencedColumnName = "ra_id" )
private AddressModel address;
//getters and setters
}

In my code, I am first saving UserModel class to database using jpa's save(). Then, I am saving AddressModel class to database. Finally, I am saving UserToAddress class to database. It is working fine. But, If some exception arises while saving UserToAddress class, still UserModel and AddressModel will be saved in the database. How to avoid it?

1 Answer 1

1

You should ensure that all of the persistence is done within the context of a transaction. If you're using Spring then I'd highly suggest reviewing Spring's documentation regarding Transaction Management. Specifically looking at the @Transactional annotation.

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#transaction-intro

A common approach would be to have an @Service class with a method marked as @Transactional and in that method you would do all necessary work to persist all entities that should share that transaction context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.