Hi
I have to save two beans in two tables , but in case of exception during saving second I need to rollback first .
I tried to use such approaches :
1. org.springframework.transaction.annotation.Transactional annotation :
Code:
@Override
@Transactional
public void saveOrUpdate(ElementData elementData)
{
Element element = elementData.getElement();
if (element != null)
{
hibernateTemplate.saveOrUpdate(element);
hibernateTemplate.saveOrUpdate(elementData);
} else
{
hibernateTemplate.saveOrUpdate(elementData);
}
}
.............
}
2. directly using SessionFactory :
Code:
@Override
public void saveOrUpdate(ElementData elementData)
{
Element element = elementData.getElement();
if (element != null)
{
Session currentSession = sessionFactory.openSession();
currentSession.beginTransaction();
try
{
currentSession.saveOrUpdate(element);
currentSession.saveOrUpdate(elementData);
} catch (Exception e)
{
currentSession.getTransaction().rollback();
throw e;
}
currentSession.getTransaction().commit();
} else
{
hibernateTemplate.saveOrUpdate(elementData);
}
}
3. cascade=CascadeType.ALL in ElementData bean which holds Element :
Code:
@Entity
public class ElementData implements Serializable
{
public static final String DIRECT_JS_CALL = "DIRECT_JS_CALL";
private static final long serialVersionUID = 6730581106117198964L;
@Id
@GeneratedValue
private Integer id;
@Column(name = "locatorType", unique = false, nullable = false)
@Enumerated(EnumType.ORDINAL)
private LocatorType locatorType;
@Column(name = "locator", unique = false, nullable = false)
private String locator;
@Column(name = "frame", unique = false, nullable = true)
private String frame;
@Column(name = "language", unique = false, nullable = false)
@Enumerated(EnumType.ORDINAL)
private Language language;
@ManyToOne(cascade =
{ CascadeType.ALL })
@JoinColumn(name = "elementId", unique = false, nullable = false)
private Element element;
@ManyToOne
@JoinColumn(name = "updatedBy", unique = false, nullable = false)
private User updatedBy;
@Column(name = "updatedDate", unique = false, nullable = true, columnDefinition = "timestamp")
private String updatedDate;
@ManyToOne
@JoinColumn(name = "releaseId", unique = false, nullable = false)
private ReleaseEntity releaseEntity;
......
}
In all cases Element table persist Element entity no matter if exception happens during saving ElementData .
Please help me to rollback Element in case of exception in saving ElementData