ninja is an awesome framework but coming from a spring background, I need to use spring data jpa with ninja.
I want to Autowire a JpaRepository and use it in ninja. Although ninja uses Guice Inject. I keep getting a No implementations found for my class.
the repository:
public interface PortalUserRepository extends JpaRepository<PortalUser, Long> {
PortalUser getPortalUserByUsername(String username);
PortalUser getPortalUserByEmail(String email);
}
the injection
public class SetupDaoV2 {
#Inject
PortalUserRepository portalUserRepository;
public void setup() {
try {
List<PortalUser> portalUsers = portalUserRepository.findAll();
if (portalUsers.size() == 0) {
// Create a new user and save it
PortalUser portalUser = new PortalUser("lsadjfl", "lsdlfs", "kkk lll",
"llskfls#gmail.com", "lsdlfss#",
"lsdfls#gmail.com",
new Timestamp(System.currentTimeMillis()), Boolean.TRUE,
Boolean.TRUE, GenericStatusConstant.ACTIVE, Boolean.TRUE
);
portalUserRepository.save(portalUser);
}
}catch (Exception ex){
ex.printStackTrace();
}
}
}
the error
com.google.inject.CreationException: Unable to create injector, see
the following errors:
1) No implementation for com.bw.dd.dsl.repository.PortalUserRepository was bound.
Well, I finally had to implement the whole thing. A shame I couldn't port the wonderful features from spring data jpa into ninja. I coulda used spring, but for office policy on the project.
If someone finds a way, pls holla.
public abstract class JpaRepository<E, K> {
public abstract void create(E entity);
public abstract void edit(E entity) throws Exception;
public abstract void remove(K key) throws IllegalOrphanException, NonexistentEntityException;
public abstract List<E> findAll();
public abstract E findOne(K key);
public abstract int count();
}
public class PortalUserRepository extends JpaRepository<PortalUser, Long> {
private EntityManagerFactory emf = null;
public PortalUserRepository() {
}
public PortalUserRepository(EntityManagerFactory emf) {
this.emf = emf;
}
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(PortalUser entity) {
if (entity.getUserTokens() == null) {
entity.setUserTokens(new ArrayList<UserToken>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Collection<UserToken> attachedUserTokens = new ArrayList<UserToken>();
for (UserToken userTokensUserTokenToAttach : entity.getUserTokens()) {
userTokensUserTokenToAttach = em.getReference(userTokensUserTokenToAttach.getClass(), userTokensUserTokenToAttach.getId());
attachedUserTokens.add(userTokensUserTokenToAttach);
}
entity.setUserTokens(attachedUserTokens);
em.persist(entity);
for (UserToken userTokensUserToken : entity.getUserTokens()) {
PortalUser oldPortalUserOfUserTokensUserToken = userTokensUserToken.getPortalUser();
userTokensUserToken.setPortalUser(entity);
userTokensUserToken = em.merge(userTokensUserToken);
if (oldPortalUserOfUserTokensUserToken != null) {
oldPortalUserOfUserTokensUserToken.getUserTokens().remove(userTokensUserToken);
oldPortalUserOfUserTokensUserToken = em.merge(oldPortalUserOfUserTokensUserToken);
}
}
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(PortalUser entity) throws Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
PortalUser persistentPortalUser = em.find(PortalUser.class, entity.getId());
Collection<UserToken> userTokensOld = persistentPortalUser.getUserTokens();
Collection<UserToken> userTokensNew = entity.getUserTokens();
List<String> illegalOrphanMessages = null;
for (UserToken userTokensOldUserToken : userTokensOld) {
if (!userTokensNew.contains(userTokensOldUserToken)) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("You must retain UserToken " + userTokensOldUserToken + " since its entity field is not nullable.");
}
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
Collection<UserToken> attachedUserTokensNew = new ArrayList<UserToken>();
for (UserToken userTokensNewUserTokenToAttach : userTokensNew) {
userTokensNewUserTokenToAttach = em.getReference(userTokensNewUserTokenToAttach.getClass(), userTokensNewUserTokenToAttach.getId());
attachedUserTokensNew.add(userTokensNewUserTokenToAttach);
}
userTokensNew = attachedUserTokensNew;
entity.setUserTokens(userTokensNew);
entity = em.merge(entity);
for (UserToken userTokensNewUserToken : userTokensNew) {
if (!userTokensOld.contains(userTokensNewUserToken)) {
PortalUser oldPortalUserOfUserTokensNewUserToken = userTokensNewUserToken.getPortalUser();
userTokensNewUserToken.setPortalUser(entity);
userTokensNewUserToken = em.merge(userTokensNewUserToken);
if (oldPortalUserOfUserTokensNewUserToken != null && !oldPortalUserOfUserTokensNewUserToken.equals(entity)) {
oldPortalUserOfUserTokensNewUserToken.getUserTokens().remove(userTokensNewUserToken);
oldPortalUserOfUserTokensNewUserToken = em.merge(oldPortalUserOfUserTokensNewUserToken);
}
}
}
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Long id = entity.getId();
if (findOne(id) == null) {
throw new NonexistentEntityException("The entity with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void remove(Long key) throws IllegalOrphanException, NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
PortalUser portalUser;
try {
portalUser = em.getReference(PortalUser.class, key);
portalUser.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The portalUser with id " + key + " no longer exists.", enfe);
}
List<String> illegalOrphanMessages = null;
Collection<UserToken> userTokensOrphanCheck = portalUser.getUserTokens();
for (UserToken userTokensOrphanCheckUserToken : userTokensOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("This PortalUser (" + portalUser + ") cannot be destroyed since the UserToken " + userTokensOrphanCheckUserToken + " in its userTokens field has a non-nullable portalUser field.");
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
em.remove(portalUser);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public List<PortalUser> findAll() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(PortalUser.class));
Query q = em.createQuery(cq);
return q.getResultList();
} finally {
em.close();
}
}
public PortalUser findOne(Long key) {
EntityManager em = getEntityManager();
try {
return em.find(PortalUser.class, key);
} finally {
em.close();
}
}
public int count() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<PortalUser> rt = cq.from(PortalUser.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
public PortalUser findPortalUserByUsername(String username){
EntityManager em = getEntityManager();
try {
Query q = em.createQuery("select s from PortalUser s where s.username = '" + username + "'");
return (PortalUser)q.getSingleResult();
} finally {
em.close();
}
}
You need to mark PortalUserRepository class with #Repository as shown below:
#Repository
public interface PortalUserRepository extends JpaRepository<PortalUser, Long> {
//your methods
}
Also, ensure that you have got #EnableJPARepositories so that Spring container can scan for your repository interfaces and provide the implementations for them and then inject them into your SetupDaoV2 bean.
Related
Can someone tell me why my entityTransaction doesn't works?
rollback() has no effect, commit() too, i think also begin(). I tried to disable autocommit:
spring.datasource.auto-commit=false
spring.datasource.hikari.auto-commit=false
but there is no effect after that, still that transactions don't work. Here is my service:
#Service
public class MyService {
...
#Autowired
private final JdbcTemplate jdbcTemplate;
...
#Autowired
private EntityManagerFactory entityManagerFactory;
...
#Transactional
public ArrayList<String> executeSQL(String[] split) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
ArrayList<String> listException = new ArrayList<String>();
boolean flag = false;
for (int i = 0; i < split.length; ++i) {
String query = split[i];
try {
entityTransaction.begin();
mapList = jdbcTemplate.queryForList(query);
entityTransaction.commit();
listException.add("Success!");
} catch (Exception e1) {
entityTransaction.rollback();
try {
entityTransaction.begin();
int rows = jdbcTemplate.update(query);
entityTransaction.commit();
listException.add("Sucesss! { [" + rows + "] <-- affected rows }");
} catch (Exception e2) {
entityTransaction.rollback();
flag = true;
listException.add(e2.getCause().getMessage());
}
}
}
entityManager.close();
if(flag){
mapList = emptyMapList;
updateFlag = false;
}
else{
updateFlag = true;
}
return listException;
}
...
I have an "XAManager" class that I'm using for a JCA component inside WildFly 13.
In the standalone-full.xml the resource adapter in question is defined as so:
...
<resource-adapter id="myTest.ear#LuceneConnector-ra-impl-0.1.0.rar">
<archive>
myTest.ear#LuceneConnector-ra-impl-0.1.0.rar
</archive>
<transaction-support>XATransaction</transaction-support>
<connection-definitions>
<connection-definition class-name="com.impl.LuceneManagedConnectionFactory" jndi-name="java:jboss/eis/LuceneConnector" enabled="true" use-java-context="true" pool-name="LuceneConnection" use-ccm="true">
<xa-pool>
<min-pool-size>0</min-pool-size>
<max-pool-size>10</max-pool-size>
<prefill>false</prefill>
<use-strict-min>false</use-strict-min>
<flush-strategy>FailingConnectionOnly</flush-strategy>
<pad-xid>false</pad-xid>
<wrap-xa-resource>true</wrap-xa-resource>
</xa-pool>
<security>
<application/>
</security>
</connection-definition>
</connection-definitions>
</resource-adapter>
....
This class is being used in the ManagedConnection class of the JCA, being returned in the getXAResource() method:
public XAResource getXAResource()
throws ResourceException {
if (this.xaResource == null) {
this.xaResource = new LuceneXAManager(this);
}
if (LuceneManagedConnection.LOGGER.isDebugEnabled()) {
LuceneManagedConnection.LOGGER.debug("XAResource=" + this.xaResource);
}
return this.xaResource;
}
The class definition is as follows:
public class LuceneXAManager
implements XAResource {
static final String _CVS = "$Revision: 1.12 $";
private static final Logger LOGGER = Logger.getLogger(IndexWriter.class);
private LuceneManagedConnection lmc = null;
// private final CACClientLocal cacClientLocal = null;
// private final CACCommunityLocal cacCommunityLocal = null;
public LuceneXAManager(final LuceneManagedConnection lmc) {
this.lmc = lmc;
}
/**
* {#inheritDoc}
*/
public void commit(final Xid xid, final boolean arg1)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("commit transaction : " + xid + " int " + arg1);
}
List<LuceneDocumentTransferWrapper> tasks = this.lmc.getLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
if (tasks != null) {
TransactionManager tm = null;
Transaction tx = null;
try {
InitialContext ctx = new InitialContext();
tm = (TransactionManager)ctx.lookup("java:jboss/TransactionManager");
tx = tm.suspend();
UserTransaction ut = (UserTransaction)ctx.lookup("java:jboss/UserTransaction");
ut.begin();
for (LuceneDocumentTransferWrapper wrapper : tasks) {
String operation = wrapper.getCommand();
Object dataObject = wrapper.getDataObject();
IndexWriter writer = null;
if (wrapper.getCommunityId() != null) {
if (LuceneManagedConnection.DO_RECREATE_INDEX.equals(operation)) {
IndexWriterManager.createNewVNIndexFor(this.loadCommunity(wrapper.getCommunityId()));
continue;
} else {
writer = IndexWriterManager.getVNWriterFor(wrapper.getCommunityId());
if (writer == null) {
writer = IndexWriterManager.getVNWriterFor(this.loadCommunity(wrapper.getCommunityId()));
}
}
if (writer == null) {
throw new IllegalArgumentException("Failed to get index writer for community " + wrapper.getCommunityId());
}
} else if (wrapper.getClientId() != null) {
if (LuceneManagedConnection.DO_RECREATE_INDEX.equals(operation)) {
IndexWriterManager.createNewIndexFor(this.loadClient(wrapper.getClientId()));
continue;
} else {
writer = IndexWriterManager.getWriterFor(wrapper.getClientId());
if (writer == null) {
writer = IndexWriterManager.getWriterFor(this.loadClient(wrapper.getClientId()));
}
}
if (writer == null) {
throw new IllegalArgumentException("Failed to get index writer for client " + wrapper.getClientId());
}
} else {
throw new IllegalArgumentException("Have no clientId or communityId");
}
if (LuceneManagedConnection.DO_DELETE_DOCUMENTS.equals(operation)) {
List<Long> documentIds = (List<Long>)dataObject;
writer.deleteDocuments(documentIds);
} else if (LuceneManagedConnection.DO_INDEX_DOCUMENT.equals(operation)) {
Document document = (Document)dataObject;
writer.addDocument(document);
} else if (LuceneManagedConnection.DO_UPDATE_INDEX.equals(operation)) {
Document document = (Document)dataObject;
if (Document.DOCUMENT_STATUS_ACTIVE.equals(document.getStatus())
|| Document.DOCUMENT_STATUS_WAITING.equals(document.getStatus())
|| Document.DOCUMENT_STATUS_OUTDATED.equals(document.getStatus())) {
writer.updateDocument(document, null);
} else {
writer.deleteDocument(document);
}
} else if (LuceneManagedConnection.DO_INDEX_CONTAINER.equals(operation)) {
Container container = (Container)dataObject;
writer.deleteContainer(container.getRfid());
writer.addContainer(container);
} else {
throw new IllegalArgumentException(" Wrong command " + operation);
}
}
ut.commit();
} catch (Exception e) {
LuceneXAManager.LOGGER.error("Failed to handle commit for transaction " + xid, e);
HashSet<Long> failedDocuments = new HashSet<Long>();
for (LuceneDocumentTransferWrapper wrapper : tasks) {
failedDocuments.clear();
if (LuceneManagedConnection.DO_DELETE_DOCUMENTS.equals(wrapper.getCommand())) {
failedDocuments.addAll((List)wrapper.getDataObject());
} else if (LuceneManagedConnection.DO_INDEX_DOCUMENT.equals(wrapper.getCommand())) {
failedDocuments.add(((Document)wrapper.getDataObject()).getId());
} else if (LuceneManagedConnection.DO_UPDATE_INDEX.equals(wrapper.getCommand())) {
failedDocuments.add(((Document)wrapper.getDataObject()).getId());
}
for (Long id : failedDocuments) {
LuceneXAManager.LOGGER.error("Possible Lucene index corruption - failed to '" + wrapper.getCommand() + "' document (id=" + id
+ ")");
}
}
throw new XAException(XAException.XAER_RMFAIL);
} finally {
try {
if (tm != null && tx != null) {
tm.resume(tx);
}
} catch (Exception e) {
LuceneXAManager.LOGGER.error("Error while close resume session", e);
}
this.lmc.removeLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
}
}
}
/**
* {#inheritDoc}
*/
public void end(final Xid xid, final int arg1)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("end transaction : " + xid);
}
}
/**
* {#inheritDoc}
*/
public void forget(final Xid xid)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("forget transaction : " + xid);
}
this.lmc.removeLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
}
/**
* {#inheritDoc}
*/
public int getTransactionTimeout()
throws XAException {
return 0;
}
/**
* {#inheritDoc}
*/
public boolean isSameRM(final XAResource arg0)
throws XAException {
return false;
}
/**
* {#inheritDoc}
*/
public int prepare(final Xid xid)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("prepare transaction : " + xid);
}
List<LuceneDocumentTransferWrapper> tasks = this.lmc.getLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
List<Long> clientWriter = new ArrayList<Long>();
List<Long> communityWriter = new ArrayList<Long>();
if (tasks != null) {
for (LuceneDocumentTransferWrapper wrapper : tasks) {
if (wrapper.getCommunityId() != null) {
if (!communityWriter.contains(wrapper.getCommunityId())) {
communityWriter.add(wrapper.getCommunityId());
}
} else {
if (!clientWriter.contains(wrapper.getClientId())) {
clientWriter.add(wrapper.getClientId());
}
}
}
}
TransactionManager tm = null;
try {
InitialContext ctx = new InitialContext();
tm = (TransactionManager)ctx.lookup(CACBean.JDNI_TX_MANAGER);
tm.suspend();
UserTransaction ut = (UserTransaction)ctx.lookup(CACBean.JDNI_USERTRANACTION);
ut.begin();
for (Long clientId : clientWriter) {
IndexWriter writer = IndexWriterManager.getWriterFor(clientId);
if (writer == null) {
if (IndexWriterManager.getWriterFor(this.loadClient(clientId)) == null) {
throw new IllegalArgumentException("Failed to get index writer for client " + clientId);
}
}
}
for (Long communityId : communityWriter) {
IndexWriter writer = IndexWriterManager.getVNWriterFor(communityId);
if (writer == null) {
if (IndexWriterManager.getVNWriterFor(this.loadCommunity(communityId)) == null) {
throw new IllegalArgumentException("Failed to get index writer for community " + communityId);
}
}
}
ut.commit();
} catch (Exception e) {
LuceneXAManager.LOGGER.error("Failed to handle prepare for transaction " + xid, e);
throw new XAException(XAException.XAER_RMFAIL);
} finally {
// try {
// if (tm != null && tx != null) {
// tm.resume(tx);
// }
// } catch (Exception e) {
// LuceneXAManager.LOGGER.warn("Error while close resume session", e);
// }
}
return XAResource.XA_OK;
}
/**
* {#inheritDoc}
*/
public Xid[] recover(final int arg0)
throws XAException {
return null;
}
/**
* {#inheritDoc}
*/
public void rollback(final Xid xid)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("rollback transaction : " + xid);
}
this.lmc.removeLuceneDocumentTransferWrapper(xid.getGlobalTransactionId());
}
/**
* {#inheritDoc}
*/
public boolean setTransactionTimeout(final int arg0)
throws XAException {
return false;
}
/**
* {#inheritDoc}
*/
public void start(final Xid arg0, final int arg1)
throws XAException {
if (LuceneXAManager.LOGGER.isDebugEnabled()) {
LuceneXAManager.LOGGER.debug("start transaction : " + arg0 + " int " + arg1);
}
}
private Client loadClient(final Long clientId)
throws RemoteException, CreateException, NamingException, CACException {
....
return client;
}
private Community loadCommunity(final Long communityId)
throws RemoteException, CreateException, NamingException, CACException {
....
return community;
}
}
The problem I'm having is that when trying to get the UserTransaction via JNDI I get Caused by: javax.naming.NameNotFoundException: UserTransaction [Root exception is java.lang.IllegalStateException: WFLYEJB0137: Only session and message-driven beans with bean-managed transaction demarcation are allowed to access UserTransaction]
I tried annotating my class with #Stateless and #TransactionManagement(TransactionManagementType.BEAN) to get over this issue but to no use.
I've also tried injecting the UserTransaction via #Inject UserTransaction but in this case the UserTransaction is null.
Any ideas ?
I have a Patients entity class which auto generates an id:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "personId", nullable = false, unique = true)
private Long personId;
public void copy (Patients patient) {
if (patient.getNationality() != null)
this.setNationality(patient.getNationality());
if (patient.getGivenName() != null)
this.setGivenName(patient.getGivenName());
if (patient.getMiddleName() != null)
this.setMiddleName(patient.getMiddleName());
if (patient.getPrefix() != null)
this.setPrefix(patient.getPrefix());
}
/**
* #return PERSONID
*/
public int getPersonId() {
return personId;
}
My addPerson in PersonDaoImpl :
public Patients addPerson(Patients person) {
Patients p = new Patients(person);
try {
em = factory.createEntityManager();
em.getTransaction().begin();
SimpleDateFormat sdfr = new SimpleDateFormat("yyyy-MM-
dd'T'HH:mm:ss.SSS+05:30");
Date date = new Date();
String dateCreated = sdfr.format(date);
p.setDateCreated(dateCreated);
em.persist(p);
em.getTransaction().commit();
} catch (Exception e) {
em.getTransaction().rollback();
log.error("Exception caught :: " + e);
p = null;
}
em.close();
return p;
}
My update api in person service class:
#PUT
#Path("/person-manager-resource/updatePersonById")
#Produces("application/json")
#Consumes("application/json")
public Response update(Patients person) {
log.info("Inside UpdatePerson");
log.info(person.getPersonId());
dao = new PersonDaoImpl();
ObjectMapper mapper = new ObjectMapper();
person1 = dao.updatePerson(person);
String result = "";
try {
result = mapper.writeValueAsString(person1);
log.info("Person updated :: " + result);
} catch (JsonProcessingException e) {
log.info("Exception Caught :: " + e);
}
if (person1 != null) {
return Response.
status(Response.Status.OK.getStatusCode()).
entity(result).
build();
} else {
return Response.
status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).
entity(result).
build();
}
}
UpdatePerson:
public Patients updatePerson(Patients updatedPatient) {
Patients dbPatient = new Patients();
TypedQuery<Patients> query = null;
ObjectMapper mapper = new ObjectMapper();
try {
em = factory.createEntityManager();
String identifier = updatedPatient.getPersonIdentifiers().getIdentifier();
String queryStr = "SELECT c FROM Patients c where c.personIdentifiers.identifier = '" + identifier + "'";
query = em.createQuery(queryStr, Patients.class);
dbPatient = query.getSingleResult();
dbPatient.copy(updatedPatient);
em.getTransaction().begin();
em.merge(dbPatient);
em.getTransaction().commit();
} catch (Exception e) {
log.error("Exception caught :: " + e);
em.getTransaction().rollback();
dbPatient = null;
}
em.close();
return dbPatient;
}
I pass a json object through my REST api to create a patient entry:
{
"personId": 5,
"prefix": null,
"givenName": "Pooja roy",
"middleName": null
}
Now this is going fine. I take the same object, which now contains the auto-generated personId, in an api which is supposed to update the object. I pass the json in the Patients entity object. When I print this whole object, the personId is null.
Since it is null and primary key, I can't do a merge. I have to manually update the database object, which is a very lengthy process.
Any ideas why it is coming as null and how I can retrieve it?
I am using postgres.
I think the whole problem is caused by the implementation of the updatePerson method. You should implement the method as follows and it should work as expected, assuming the updatedPatient instance is a persistent entity (meaning it has an ID field set):
public Patients updatePerson(Patients updatedPatient) {
Patients mergedPatient = new Patients();
try {
em = factory.createEntityManager();
em.getTransaction().begin();
mergedPatient = em.merge(updatedPatient);
em.getTransaction().commit();
} catch (Exception e) {
log.error("Exception caught :: " + e);
em.getTransaction().rollback();
}
em.close();
return mergedPatient;
}
Now mergedPatient should contain the synchronized state.
Update:
alternative solution
For whatever reason you cannot use a setter for the ID field. Then the following might solve your problem:
public Patients updatePerson(Patients updatedPatient) {
Patients dbPatient = new Patients();
try {
em = factory.createEntityManager();
String identifier = updatedPatient.getPersonIdentifiers().getIdentifier();
em.getTransaction().begin();
dbPatient = em.find(Patients.class, Long.parseLong(identifier));
dbPatient.copy(updatedPatient);
em.getTransaction().commit();
} catch (Exception e) {
// ..:
dbPatient = null;
}
em.close();
return dbPatient;
}
As the em.find() method is executed inside of a transaction, the object returned is managed, which means any changes to that returned instance will be synchronized with the database when the transaction commits.
PersonId is an auto generated id. So, jpa doesn't allow for me to set a setter for personId. We only have getPersonId() method in the entity class.
So, in updatePerson(Patients person), when I am passing the person object, every setter is called and the object is thus created. Since, personId doesn't have a setter method, it is returned as null in that object.
public UMRResultObject insertDocumentation(UMRDocumentationDTO documentationDTO)
{
Session session = UMRHibernateUtil.getUmrSession();
Transaction tx = null;
List<UMRDTO> duplicateDocumentationList=null;
String objectType =documentationDTO.getId().getObjectType();
String objectName =documentationDTO.getId().getObjectName();
try
{
duplicateDocumentationList = dao.getFilteredDocumentationList(objectType, objectName, false, session);
if(duplicateDocumentationList.isEmpty())
{
tx = session.beginTransaction();
dao.insertDocumentation(documentationDTO, session);
tx.commit();
ro.setSuccess(true);
ro.getMessages().add("Record Inserted Successfully");
if (ro.isSuccess())
{
if("Domain".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(objectName, documentationDTO.getDocumentationLink());
}
else if("DomainCombo".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(objectName, documentationDTO.getDocumentationLink());
}
return ro;
}
}
else
{
ro.getMessages().add("Documentation for '" + objectName + "' "
+ objectType+ " already exists! \n");
logger.info("Documentation for '" + objectName + "' "
+ objectType+ " already exists! \n");
}
}
return ro;
}
public UMRResultObject updateDocumentation(UMRDocumentationDTO documentationDTO)
{
Session session = UMRHibernateUtil.getUmrSession();
Transaction tx = null;
try
{
String objectType = documentationDTO.getId().getObjectType();
if("Domain".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(documentationDTO.getId().getObjectName(), documentationDTO.getDocumentationLink());
}
else if("DomainCombo".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(documentationDTO.getId().getObjectName(), documentationDTO.getDocumentationLink());
}
tx = session.beginTransaction();
dao.updateDocumentation(documentationDTO, session);
tx.commit();
ro.setSuccess(true);
ro.getMessages().add("Record Updated Successfully");
if(ro.isSuccess())
{
if("Domain".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(objectName, documentationDTO.getDocumentationLink());
}
else if("DomainCombo".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(objectName, documentationDTO.getDocumentationLink());
}
return ro;
}
}
I dont want to ducplicate the code in if(ro.isSuccess()) and want to refactor the code but unable to get any further from this
I tried making another method for it unable to use documentationDTO what should I do
You can do something like this:
if(ro.isSuccess()){
populateMap(objectType, objectName, documentationDTO);
return ro;
}
Method would be like below:
private void populateMap(String objectType, String objectName, UMRDocumentationDTO documentationDTO){
if("Domain".equals(objectType) || "DomainCombo".equals(objectType))
{
MMTUtil.getDomainDocumentationMap().put(objectName, documentationDTO.getDocumentationLink());
}
}
I am creating web service for project and I want consume it from my Android application.
I am using Java EE, EJB, JAX-RS, JPA, MySQL and Glassfish as application server.
But I am having problem with encoding of my JSON feed, I am missing some characters from UTF-8. Some characters are not being displayed and instead of them I get ?.
Link of web service: http://recipesgenie.com:8080/Horoskopium/api/day
REST service code:
#Path(value = "/")
#ApplicationPath(value = "api")
public class RestService extends Application{
#PersistenceContext
EntityManager em;
// http://localhost:8080/Horoskopium/api/day
// http://localhost:8080/Horoskopium/api/day?lang=sr
#GET
#Path(value = "/day")
#Produces(MediaType.APPLICATION_JSON+ ";charset=utf-8")
public List<Day> getToday(#QueryParam ("lang") String lang){
Query q = em.createQuery("SELECT d FROM Day d ORDER BY d.id DESC");
return q.setMaxResults(12).getResultList();
}
#GET
#Path(value = "/love")
#Produces(MediaType.APPLICATION_JSON+ ";charset=utf-8")
public List<Love> getLove(#QueryParam ("lang") String lang){
Query q = em.createQuery("SELECT l FROM Love l ORDER BY l.id DESC");
return q.setMaxResults(12).getResultList();
}
#GET
#Path(value = "/week")
#Produces(MediaType.APPLICATION_JSON+ ";charset=utf-8")
public List<Week> getWeek(#QueryParam ("lang") String lang){
Query q = em.createQuery("SELECT w FROM Week w ORDER BY w.id DESC");
return q.setMaxResults(12).getResultList();
}
#GET
#Path(value = "/month")
#Produces(MediaType.APPLICATION_JSON+ ";charset=utf-8")
public List<Month> getMonth(#QueryParam ("lang") String lang){
Query q = em.createQuery("SELECT m FROM Month m ORDER BY m.id DESC");
return q.setMaxResults(12).getResultList();
}
}
I have also TimerService that connect to another server and read JSON and save it to my MySQL database.
This JSON response from another server that I am reading and parsing with Gson into my database: http://aplikacije-za-android.com/apps/horoskopium/examples/nedeljnihoroskop.php
#Singleton
public class TimerService {
#EJB
HoroscopeEJB horoscopeEJB;
HoroscopeParser horoscopeParser;
#Schedule(dayOfWeek = "*", hour="0-6", persistent = false)
public void downloadTodayHoroscope() throws Exception {
System.out.println("upisujem today ");
saveTodayHoroscope();
}
#Schedule(dayOfWeek = "*", hour="0-6", persistent = false)
public void downloadLoveHoroscope() throws Exception {
System.out.println("upisujem love ");
saveLoveHoroscope();
}
#Schedule(dayOfWeek = "Mon", hour="0/2", persistent = false)
public void downloadWeekHoroscope() throws Exception {
System.out.println("upisujem week ");
saveWeekHoroscope();
}
#Schedule(dayOfMonth = "1", hour = "4/3", persistent = false)
public void downloadMonthHoroscope() throws Exception {
System.out.println("upisujem month ");
saveMonthHoroscope();
}
public void saveTodayHoroscope() throws Exception {
HoroscopeFeed horoscope = getTodayHoroscope();
if (horoscope != null && horoscope.getHoroscope().size() > 0) {
for (int i = 0; i < horoscope.getHoroscope().size(); i++) {
Day d = new Day();
d.setText(horoscope.getHoroscope().get(i).getTxtHrs());
horoscopeEJB.addTodayHoroscope(d);
}
}
}
public void saveLoveHoroscope() throws Exception {
HoroscopeFeed horoscope = getLoveHoroscope();
if (horoscope != null && horoscope.getHoroscope().size() > 0) {
for (int i = 0; i < horoscope.getHoroscope().size(); i++) {
Love l = new Love();
l.setText(horoscope.getHoroscope().get(i).getTxtHrs());
horoscopeEJB.addLoveHoroscope(l);
}
}
}
public void saveWeekHoroscope() throws Exception {
HoroscopeFeed horoscope = getWeekHoroscope();
if (horoscope != null && horoscope.getHoroscope().size() > 0) {
for (int i = 0; i < horoscope.getHoroscope().size(); i++) {
Week w = new Week();
w.setText(horoscope.getHoroscope().get(i).getTxtHrs());
horoscopeEJB.addWeekHoroscope(w);
}
}
}
public void saveMonthHoroscope() throws Exception {
HoroscopeFeed horoscope = getMonthHoroscope();
if (horoscope != null && horoscope.getHoroscope().size() > 0) {
for (int i = 0; i < horoscope.getHoroscope().size(); i++) {
Month m = new Month();
m.setText(horoscope.getHoroscope().get(i).getTxtHrs());
horoscopeEJB.addMonthHoroscope(m);
}
}
}
public HoroscopeFeed getTodayHoroscope() throws Exception {
horoscopeParser = new HoroscopeParser();
return horoscopeParser.getTodayHoroscope("http://aplikacije-za-android.com/apps/horoskopium/examples/dnevnihoroskop.php");
}
public HoroscopeFeed getWeekHoroscope() throws Exception {
horoscopeParser = new HoroscopeParser();
return horoscopeParser.getWeekHoroscope("http://aplikacije-za-android.com/apps/horoskopium/examples/nedeljnihoroskop.php");
}
public HoroscopeFeed getLoveHoroscope() throws Exception {
horoscopeParser = new HoroscopeParser();
return horoscopeParser.getLoveHoroscope("http://aplikacije-za-android.com/apps/horoskopium/examples/dnevniljubavnihoroskop.php");
}
public HoroscopeFeed getMonthHoroscope() throws Exception {
horoscopeParser = new HoroscopeParser();
return horoscopeParser.getMonthHoroscope("http://aplikacije-za-android.com/apps/horoskopium/examples/mesecnihoroskop.php");
}
}
EJB code:
#Stateless
#LocalBean
public class HoroscopeEJB {
#PersistenceContext
EntityManager em;
public void addTodayHoroscope(Day day){
boolean ifExist = checkDaily(day.getText());
if(!ifExist){
em.merge(day);
} else{
System.out.println("Imam vec dnevni u bazi");
}
}
public void addLoveHoroscope(Love love){
boolean ifExist = checkLove(love.getText());
if(!ifExist){
em.merge(love);
}
}
public void addWeekHoroscope(Week week){
week.getText();
boolean ifExist = checkWeek(week.getText());
if(!ifExist){
em.merge(week);
}
}
public void addMonthHoroscope(Month month){
boolean ifExist = checkMonth(month.getText());
if(!ifExist){
em.merge(month);
}
}
private boolean checkDaily(String text){
List<Day> results = em.createQuery("SELECT d FROM Day d WHERE d.text = :text")
.setParameter("text", text).getResultList();
if(results.size() > 0){
return true;
} else{
return false;
}
}
private boolean checkLove(String text){
List<Love> results = em.createQuery("SELECT l FROM Love l WHERE l.text = :text")
.setParameter("text", text).getResultList();
if(results.size() > 0){
return true;
} else{
return false;
}
}
private boolean checkWeek(String text){
List<Week> results = em.createQuery("SELECT w FROM Week w WHERE w.text = :text")
.setParameter("text", text).getResultList();
if(results.size() > 0){
return true;
} else{
return false;
}
}
private boolean checkMonth(String text){
List<Month> results = em.createQuery("SELECT m FROM Month m WHERE m.text = :text")
.setParameter("text", text).getResultList();
if(results.size() > 0){
return true;
} else{
return false;
}
}
}