[
Date Prev][
Date Next][
Thread Prev][
Thread Next][
Date Index][
Thread Index]
[
List Home]
[eclipselink-users] JPA on GlassfishV3 prelude with Updateproblem
|
Hello,
I'm trying to update an Entity with JPA true EclipseLink on Glassfish.
I set OptimisticLocking(type=OptimisticLockingType.ALL_COLUMNS).
If Glassfish is freshli started, the Update is OK produce the Fallowing SQL:
UPDATE GESTHO.T_ROLE SET ROLE_LOCK = ? WHERE ((ROLE_ID = ?) AND ((((((ROLE_NAME = ?) AND (CRE_DAT = ?)) AND (CRE_KURZZ = ?)) AND (MUT_DAT = ?)) AND (MUT_KURZZ = ?)) AND (ROLE_LOCK IS NULL)))
bind => [null, 10, mr, 2009-04-14 12:07:33.0, BM, 2009-04-21 10:26:58.0, BM]|#]
respectivly:
UPDATE GESTHO.T_ROLE SET ROLE_LOCK = ? WHERE ((ROLE_ID = ?) AND ((((((ROLE_NAME = ?) AND (CRE_DAT = ?)) AND (CRE_KURZZ = ?)) AND (MUT_DAT = ?)) AND (MUT_KURZZ = ?)) AND (ROLE_LOCK = ?)))
bind => [null, 10, mr, 2009-04-14 12:07:33.0, BM, 2009-04-21 10:26:58.0, BM, 3008-08-22 08:26:58.0]|#]
But when I do an other Update of the Same Entity it results in a SQL like:
UPDATE GESTHO.T_ROLE SET ROLE_LOCK = ? WHERE ((ROLE_ID = ?) AND ((((((ROLE_NAME = ?) AND (CRE_DAT = ?)) AND (CRE_KURZZ = ?)) AND (MUT_DAT = ?)) AND (MUT_KURZZ = ?)) AND (ROLE_LOCK = ?)))
bind => [3008-08-22 08:42:48.942, 10, mr, 2009-04-14 12:07:33.0, BM, 2009-04-21 10:41:09.0, BM, null]|#]
wich throws an OptimisticLockException in order the update never affect any rows becose "Collum = NULL" is never true;
I think it's a Caching problem, I also try to manipulate the Caching by CahingAnnotation on the Entity and in the persistence.xml without any visual effects.
For Details, the entity "User" is inherited from "Role":
Class Rule:
*********
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ch.braunvieh.argus_core.usermgmt.db;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.annotations.Cache;
import org.eclipse.persistence.annotations.CacheCoordinationType;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
* @author bm
*/
@Entity
@Table(name = "T_ROLE", catalog = "", schema = "GESTHO", uniqueConstraints = {@UniqueConstraint(columnNames = {"ROLE_NAME"})})
@OptimisticLocking(type=OptimisticLockingType.ALL_COLUMNS)
@Cache(expiry=10, alwaysRefresh=true, disableHits=true, coordinationType=CacheCoordinationType.INVALIDATE_CHANGED_OBJECTS)
@NamedQueries({@NamedQuery(name = "Role.findAll", query = "SELECT r FROM Role r"), @NamedQuery(name = "Role.findByRoleId", query = "SELECT r FROM Role r WHERE r.roleId = :roleId"), @NamedQuery(name = "Role.findByRoleName", query = "SELECT r FROM Role r WHERE r.roleName = :roleName"), @NamedQuery(name = "Role.findByCreDat", query = "SELECT r FROM Role r WHERE r.rCreDat = :rCreDat"), @NamedQuery(name = "Role.findByCreKurzz", query = "SELECT r FROM Role r WHERE r.rCreKurzz = :rCreKurzz"), @NamedQuery(name = "Role.findByMutDat", query = "SELECT r FROM Role r WHERE r.rMutDat = :rMutDat"), @NamedQuery(name = "Role.findByMutKurzz", query = "SELECT r FROM Role r WHERE r.rMutKurzz = :rMutKurzz"), @NamedQuery(name = "Role.findByRoleType", query = "SELECT r FROM Role r WHERE r.roleType = :roleType")})
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="ROLE_TYPE", discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue("ROLE")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "ROLE_ID", nullable = false)
@SequenceGenerator(name="sTROLE", allocationSize=1, initialValue=10, sequenceName="S_T_ROLE")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="sTROLE")
private Long roleId;
@Basic(optional = false)
@Column(name = "ROLE_NAME", nullable = false, length = 30)
private String roleName;
@Basic(optional = false)
@Column(name = "CRE_DAT", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date rCreDat;
@Basic(optional = false)
@Column(name = "CRE_KURZZ", nullable = false, length = 20)
private String rCreKurzz;
@Basic(optional = false)
@Column(name = "MUT_DAT", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date rMutDat;
@Basic(optional = false)
@Column(name = "MUT_KURZZ", nullable = false, length = 20)
private String rMutKurzz;
@Column(name = "ROLE_TYPE", length = 20)
private String roleType;
@Column(name = "ROLE_LOCK", nullable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date lock;
// @OneToOne(cascade = CascadeType.ALL, mappedBy = "role")
// private User user;
// @OneToOne(cascade = CascadeType.ALL, mappedBy = "role")
// private UserGroup userGroup;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "rlpropRoleId")
private Collection<RoleProperty> rolePropertyCollection;
public Role() {
}
public Role(Long roleId) {
this.roleId = roleId;
}
public Role(Long roleId, String roleName, Date creDat, String creKurzz, Date mutDat, String mutKurzz) {
this.roleId = roleId;
this.roleName = roleName;
this.rCreDat = creDat;
this.rCreKurzz = creKurzz;
this.rMutDat = mutDat;
this.rMutKurzz = mutKurzz;
}
public void addRoleProperty(RoleProperty roleProperty) {
if (getRolePropertyCollection() == null){
setRolePropertyCollection(new ArrayList<RoleProperty>());
}
getRolePropertyCollection().add(roleProperty);
}
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Date getRCreDat() {
return rCreDat;
}
public void setRCreDat(Date rCreDat) {
this.rCreDat = rCreDat;
}
public String getRCreKurzz() {
return rCreKurzz;
}
public void setRCreKurzz(String rCreKurzz) {
this.rCreKurzz = rCreKurzz;
}
public Date getRMutDat() {
return rMutDat;
}
public void setRMutDat(Date rMutDat) {
this.rMutDat = rMutDat;
}
public String getRMutKurzz() {
return rMutKurzz;
}
public void setRMutKurzz(String rMutKurzz) {
this.rMutKurzz = rMutKurzz;
}
public String getRoleType() {
return roleType;
}
public void setRoleType(String roleType) {
this.roleType = roleType;
}
public Date getLock() {
return lock;
}
public void setLock(Date lock) {
this.lock = lock;
}
public boolean isLock() {
return (lock != null);
}
public void setLock(boolean lock) {
if (lock) {
this.lock = new Date(System.currentTimeMillis());
} else {
this.lock = null;
}
}
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public UserGroup getUserGroup() {
// return userGroup;
// }
//
// public void setUserGroup(UserGroup userGroup) {
// this.userGroup = userGroup;
// }
//
public Collection<RoleProperty> getRolePropertyCollection() {
if (rolePropertyCollection == null) {
rolePropertyCollection = new ArrayList<RoleProperty>();
}
return rolePropertyCollection;
}
public void setRolePropertyCollection(Collection<RoleProperty> rolePropertyCollection) {
this.rolePropertyCollection = rolePropertyCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (roleId != null ? roleId.hashCode() : 0);
hash += (roleType != null ? roleType.hashCode() : 0);
/* TODO logging wieder entfernen */
System.out.println(this.toString() + " hashCode:" + hash);
return hash;
}
@Override
public boolean equals(Object object) {
/* TODO logging wieder entfernen */
System.out.println(this.toString() + " equals " + object.toString() + "???????");
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Role)) {
return false;
}
Role other = (Role) object;
if ((this.roleId == null && other.roleId != null) || (this.roleId != null && !this.roleId.equals(other.roleId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "ch.braunvieh.argus_core.usermgmt.db.Role[roleId=" + roleId + "]";
}
}
**********************
Class User:
*********
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ch.braunvieh.argus_core.usermgmt.db;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import org.eclipse.persistence.annotations.OptimisticLocking;
import org.eclipse.persistence.annotations.OptimisticLockingType;
/**
*
* @author bm
*/
@Entity
@Table(name = "T_USER", catalog = "", schema = "GESTHO")
@OptimisticLocking(type=OptimisticLockingType.ALL_COLUMNS)
@NamedQueries({@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"), @NamedQuery(name = "User.findByRoleId", query = "SELECT u FROM User u WHERE u.roleId = :roleId"), @NamedQuery(name = "User.findByUsrFirstname", query = "SELECT u FROM User u WHERE u.usrFirstname = :usrFirstname"), @NamedQuery(name = "User.findByUsrLastname", query = "SELECT u FROM User u WHERE u.usrLastname = :usrLastname"), @NamedQuery(name = "User.findByUsrEmail", query = "SELECT u FROM User u WHERE u.usrEmail = :usrEmail"), @NamedQuery(name = "User.findByUsrWatchedlogins", query = "SELECT u FROM User u WHERE u.usrWatchedlogins = :usrWatchedlogins"), @NamedQuery(name = "User.findByUsrCountedlogins", query = "SELECT u FROM User u WHERE u.usrCountedlogins = :usrCountedlogins"), @NamedQuery(name = "User.findByCreDat", query = "SELECT u FROM User u WHERE u.creDat = :creDat"), @NamedQuery(name = "User.findByCreKurzz", query = "SELECT u FROM User u WHERE u.creKurzz = :creKurzz"), @NamedQuery(name = "User.findByMutDat", query = "SELECT u FROM User u WHERE u.mutDat = :mutDat"), @NamedQuery(name = "User.findByMutKurzz", query = "SELECT u FROM User u WHERE u.mutKurzz = :mutKurzz")})
@DiscriminatorValue("USER")
@PrimaryKeyJoinColumn(name="ROLE_ID")
public class User extends Role{
// private static final long serialVersionUID = 1L;
// @Id
// @Basic(optional = false)
// @Column(name = "ROLE_ID", nullable = false)
// private Long roleId;
@Basic(optional = false)
@Column(name = "USR_FIRSTNAME", nullable = false, length = 60)
private String usrFirstname;
@Basic(optional = false)
@Column(name = "USR_LASTNAME", nullable = false, length = 60)
private String usrLastname;
@Basic(optional = false)
@Column(name = "USR_EMAIL", nullable = false, length = 80)
private String usrEmail;
@Basic(optional = false)
@Column(name = "USR_WATCHEDLOGINS", nullable = false)
private short usrWatchedlogins;
@Basic(optional = false)
@Column(name = "USR_COUNTEDLOGINS", nullable = false)
private long usrCountedlogins;
@Basic(optional = false)
@Column(name = "CRE_DAT", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date creDat;
@Basic(optional = false)
@Column(name = "CRE_KURZZ", nullable = false, length = 20)
private String creKurzz;
@Basic(optional = false)
@Column(name = "MUT_DAT", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date mutDat;
@Basic(optional = false)
@Column(name = "MUT_KURZZ", nullable = false, length = 20)
private String mutKurzz;
// @JoinColumn(name = "ROLE_ID", referencedColumnName = "ROLE_ID", nullable = false, insertable = false, updatable = false)
// @OneToOne(optional = false)
// private Role role;
@Basic(optional = false)
@Column(name = "USR_PASSWORD", nullable = false, length = 40)
private String usrPassword;
@Transient
private boolean loggedIn;
@ManyToMany()
@JoinTable(name="GESTHO.TZ_USER_USERGROUP",
joinColumns=@JoinColumn(name="USRUGRP_USR_ROLE_ID", referencedColumnName="ROLE_ID"),
inverseJoinColumns=@JoinColumn(name="USRUGRP_UGRP_ROLE_ID", referencedColumnName="ROLE_ID"))
private Collection<UserGroup> userGroups;
public void addUserGroup(UserGroup userGroup) {
if (getUserGroups() == null){
setUsergroups(new ArrayList<UserGroup>());
}
getUserGroups().add(userGroup);
}
public Collection<UserGroup> getUserGroups() {
return userGroups;
}
public void setUsrPassword(String password){
this.usrPassword = getMD5Hash(password);
}
public boolean isUsrPasswordValidate(String password){
if (this.usrPassword == null)
return false;
System.out.println("Gespeicherter Hash: " + usrPassword);
System.out.println("Berechneter Hash : " + getMD5Hash(password));
return this.usrPassword.equalsIgnoreCase(getMD5Hash(password));
}
private String getMD5Hash(String str) {
/* Berechnung */
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(str.getBytes());
byte[] result = md5.digest();
/* Ausgabe */
StringBuffer hexStringBuff = new StringBuffer();
for (int i=0; i<result.length; i++) {
String hexString = Integer.toHexString(0xFF & result[i]);
if (hexString.length() % 2 != 0) {
// Pad with 0
hexString = "0"+hexString;
}
hexStringBuff.append(hexString);
}
return hexStringBuff.toString().toUpperCase();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public void setLoggedIn(boolean loggedIn) {
this.loggedIn = loggedIn;
}
public boolean isLoggedIn(){
return this.loggedIn;
}
public void setUsergroups(Collection<UserGroup> userGroups) {
this.userGroups = userGroups;
}
public User() {
}
// public User(Long roleId) {
// this.roleId = roleId;
// }
public User(Long roleId, String usrFirstname, String usrLastname, String usrEmail, short usrWatchedlogins, long usrCountedlogins, Date creDat, String creKurzz, Date mutDat, String mutKurzz) {
// this.roleId = roleId;
this.usrFirstname = usrFirstname;
this.usrLastname = usrLastname;
this.usrEmail = usrEmail;
this.usrWatchedlogins = usrWatchedlogins;
this.usrCountedlogins = usrCountedlogins;
this.creDat = creDat;
this.creKurzz = creKurzz;
this.mutDat = mutDat;
this.mutKurzz = mutKurzz;
}
// public Long getRoleId() {
// return roleId;
// }
// public void setRoleId(Long roleId) {
// this.roleId = roleId;
// }
public String getUsrFirstname() {
return usrFirstname;
}
public void setUsrFirstname(String usrFirstname) {
this.usrFirstname = usrFirstname;
}
public String getUsrLastname() {
return usrLastname;
}
public void setUsrLastname(String usrLastname) {
this.usrLastname = usrLastname;
}
public String getUsrEmail() {
return usrEmail;
}
public void setUsrEmail(String usrEmail) {
this.usrEmail = usrEmail;
}
public short getUsrWatchedlogins() {
return usrWatchedlogins;
}
public void setUsrWatchedlogins(short usrWatchedlogins) {
this.usrWatchedlogins = usrWatchedlogins;
}
public long getUsrCountedlogins() {
return usrCountedlogins;
}
public void setUsrCountedlogins(long usrCountedlogins) {
this.usrCountedlogins = usrCountedlogins;
}
public Date getCreDat() {
return creDat;
}
public void setCreDat(Date creDat) {
this.creDat = creDat;
}
public String getCreKurzz() {
return creKurzz;
}
public void setCreKurzz(String creKurzz) {
this.creKurzz = creKurzz;
}
public Date getMutDat() {
return mutDat;
}
public void setMutDat(Date mutDat) {
this.mutDat = mutDat;
}
public String getMutKurzz() {
return mutKurzz;
}
public void setMutKurzz(String mutKurzz) {
this.mutKurzz = mutKurzz;
}
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
@Override
public int hashCode() {
int hash = 0;
hash += (getRoleId() != null ? getRoleId().hashCode() : 0);
hash += (getRoleType() != null ? getRoleType().hashCode() : 0);
/* TODO logging wieder entfernen */
System.out.println(this.toString() + " hashCode:" + hash);
return hash;
}
@Override
public boolean equals(Object object) {
/* TODO logging wieder entfernen */
System.out.println(this.toString() + " equals " + object.toString() + "???????");
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof User)) {
return false;
}
User other = (User) object;
if ((this.getRoleId() == null && other.getRoleId() != null) || (this.getRoleId() != null && !this.getRoleId().equals(other.getRoleId()))) {
return false;
}
return true;
}
@Override
public String toString() {
return "ch.braunvieh.argus_core.usermgmt.db.User[roleId=" + getRoleId() + "]";
}
}
**************************
Code where the Update hapenz (procedure update):
Class DefultDataManager
**************************
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ch.braunvieh.argus_core.datamgmt.logic;
import ch.braunvieh.argus_core.clientmgmt.ClientUtility;
import ch.braunvieh.argus_core.usermgmt.db.RoleProperty;
import ch.braunvieh.argus_core.usermgmt.db.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.Query;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.OptimisticLockException;
import javax.persistence.Persistence;
import javax.persistence.TransactionRequiredException;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import org.eclipse.persistence.jpa.JpaHelper;
import org.eclipse.persistence.queries.StoredFunctionCall;
import org.eclipse.persistence.queries.ValueReadQuery;
import org.eclipse.persistence.sessions.Session;
import org.eclipse.persistence.sessions.factories.SessionManager;
/**
*
* @author bm
*/
public class DefaultDataManager implements DataManager{
private EntityManagerFactory emf;
public static final String DATABASEUSER = "ch.braunvieh.databaseuser";
protected String defaultPU = "ArgusB_CorePU";
public EntityManager getEntityManager() {
EntityManager em = getEntityManagerFactory().createEntityManager();
// Registrierter Benutzer?
User user = ClientUtility.getSessionBean().getUser();
if (user != null && user.isLoggedIn()){
user = em.merge(user);
if (user.getRolePropertyCollection() != null) {
for (RoleProperty roleProperty : user.getRolePropertyCollection()){
if (roleProperty.getRlpropProperty().equalsIgnoreCase(DATABASEUSER)){
// System.out.println(getDatabaseUser());
return getPersonalEntityManager(roleProperty.getRlpropValue());
}
}
}
}
// System.out.println(getDatabaseUser());
return em;
}
// private User
/*
* Damit es funktioniert brauchen die User das Connect-Recht!
* alter user bm grant connect THROUGH gestho;
*/
private EntityManager getPersonalEntityManager(String username) {
Map emProperties = new HashMap();
emProperties.put("eclipselink.oracle.proxy-type", oracle.jdbc.OracleConnection.PROXYTYPE_USER_NAME);
emProperties.put(oracle.jdbc.OracleConnection.PROXY_USER_NAME, username);
EntityManager em = getEntityManagerFactory().createEntityManager(emProperties);
return em;
}
private EntityManagerFactory getEntityManagerFactory() {
if (emf == null || !emf.isOpen()){
emf = Persistence.createEntityManagerFactory(defaultPU);
}
return emf;
}
@Override
public UserTransaction getUserTransaction() throws NamingException {
UserTransaction utx = null;
try {
utx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
} catch (NamingException e) {
throw new NamingException(e.getMessage());
}
return utx;
}
@Override
public Session getSession() {
Session serverSession = JpaHelper.getServerSession(getEntityManagerFactory());
SessionManager manager = SessionManager.getManager();
Session session = manager.getSession(defaultPU);
// session.acquireUnitOfWork().
return serverSession;
// Project project = new MyProject();
// final ServerSession serverSession = new ServerSession(project);
// EntityManagerFactory emf = new EntityManagerFactoryImpl(serverSession);
// EntityManager em = emf.createEntityManager();
}
public String getDatabaseUser() {
StoredFunctionCall functionCall = new StoredFunctionCall();
functionCall.setProcedureName("pa_sys.sGetUser");
// functionCall.addNamedArgument("EMP_ID");
functionCall.setResult("FUNCTION_RESULT", String.class);
ValueReadQuery query = new ValueReadQuery();
query.setCall(functionCall);
// query.addArgument("EMP_ID");
List args = new ArrayList();
// args.addElement(new Integer(44));
String dbUser = (String) getSession().executeQuery(query, args);
return dbUser;
}
@Override
public <T> T find(Class<T> entityClass, Object primaryKey) {
EntityManager em = getEntityManager();
T t = em.find(entityClass, primaryKey);
em.refresh(t);
return t;
}
@Override
public <T> T persist(T entity) throws DataHandlingException {
EntityManager em = getEntityManager();
try {
begin();
em.persist(entity);
em.flush();
commit();
em.refresh(entity);
} catch (Exception e) {
Logger.getLogger(DefaultDataManager.class.getName()).log(Level.SEVERE,null, e);
DataHandlingException dhe = new DataHandlingException();
dhe.setStackTrace(e.getStackTrace());
throw dhe;
}
return entity;
}
@Override
public <T> T update(T entity) throws OptimisticLockException, DataHandlingException {
T newT = null;
EntityManager em = getEntityManager();
try {
begin();
newT = em.merge(entity);
em.flush();
commit();
em.refresh(newT);
}
catch (OptimisticLockException e) {
throw e;
}
catch (TransactionRequiredException tre) {
}
catch (Exception e) {
Logger.getLogger(DefaultDataManager.class.getName()).log(Level.SEVERE,null, e);
DataHandlingException dhe = new DataHandlingException();
dhe.setStackTrace(e.getStackTrace());
throw dhe;
}
return newT;
}
@Override
public <T> T delete(T entity) throws DataHandlingException {
EntityManager em = getEntityManager();
try {
begin();
entity = em.merge(entity);
em.refresh(entity);
em.remove(entity);
commit();
} catch (OptimisticLockException e) {
throw e;
} catch (Exception e) {
Logger.getLogger(DefaultDataManager.class.getName()).log(Level.SEVERE,null, e);
DataHandlingException dhe = new DataHandlingException();
dhe.setStackTrace(e.getStackTrace());
throw dhe;
}
return entity;
}
@Override
public Query createQuery(String qlString) {
return getEntityManager().createQuery(qlString);
}
protected void begin() throws DataHandlingException {
try {
getUserTransaction().begin();
} catch (Exception e) {
DataHandlingException dhe = new DataHandlingException();
dhe.setStackTrace(e.getStackTrace());
throw dhe;
}
}
protected void commit() throws DataHandlingException {
try {
getUserTransaction().commit();
} catch (Exception e) {
DataHandlingException dhe = new DataHandlingException();
dhe.setStackTrace(e.getStackTrace());
throw dhe;
}
}
}
***************
persistence.xml
*************
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="ArgusB_CorePU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/ARGUSDatabase</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.session-name" value="ArgusB_CorePU" />
<property name="eclipselink.logging.level" value="ALL" />
<property name="eclipselink.logging.logger" value="ServerLogger" />
<!--
<property name="eclipselink.cache.type.default" value="Weak" />
<property name="eclipselink.cache.size.default" value="0" />
<property name="eclipselink.cache.shared.default" value="false" />
-->
</properties>
</persistence-unit>
</persistence>