JPA does not write to table - sql-server

I have the following JPA code, with all the values checked (ticket contains a valid bean, it ends without exception, etc.) It is executed, it does not throw any exceptions, yet in the end no data is written into the table.
I tried also retrieving a bean from the table, it also "works" (it is empty, so no data is returned).
The setup is
JBoss 6.1 Final
SQLServer 2008 Express (driver SQL JDBC 3 from MS)
The persistence code:
public String saveTicket() {
System.out.println("Controller saveTicket() ");
EntityManagerFactory factory = Persistence.createEntityManagerFactory("GesMan"); /* I know it would be better to share a single instance of factory, this is just for testing */
EntityManager entityMan = factory.createEntityManager();
entityMan.persist(this.ticket);
entityMan.close();
}
The persistence unit is
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="GesMan" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/GesManDS</jta-data-source>
<class>es.caib.gesma.gesman.Ticket</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
<property name="hibernate.transaction.manager_lookup_class"
value="org.hibernate.transaction.JBossTransactionManagerLookup"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
The datasource
<datasources>
<local-tx-datasource>
<jndi-name>GesManDS</jndi-name>
<connection-url>jdbc:sqlserver://spsigeswnt14.caib.es:1433;DatabaseName=TEST_GESMAN</connection-url>
<driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
<user-name>thisis</user-name>
<password>notthepassword</password>
<check-valid-connection-sql>SELECT * FROM dbo.Ticket</check-valid-connection-sql>
<metadata>
<type-mapping>MS SQLSERVER</type-mapping>
</metadata>
</local-tx-datasource>
</datasources>

call entityMan.flush() or transaction.commit() befor closing it, otherwise it will discard all changes queued on close.

In the end it looks like I was using the wrong approach.... In JBoss you can`t (better said, I could not get to) access JPA directly (as you would do in JSE).
I ended creating an EJB (with transactions) and passing all JPA logic there.
PS: Of course, if I am wrong please tell me (now it is more of an academic issue, but still I want to know)

Related

Infinispan file-store creates binary folders with multiple .dat files

I am using the below infinispan configuration file and running into a weird issue. On startup the application creates multiple folders (one for each digit of the byte array 0 to 255) and each folder contains .dat file (in my case idempotent.dat). Also the content of the file are FCS1 for all the files created.
What I was expecting is that it will create a single file (/ap/efts/data/stage/cache/idempotent.dat) which has all the cached objects.
Can someone please identify what is causing this issue? I am using a camel-infinispan component to create Infinispan based idempotent repository.
NOTE: This was working correctly in infinispan version 7.0. For reference, I am also providing infinispan 7.0 configuration file as well as the spring bean configuration for idempotent repository.
infinispan.xml (10.0)
<?xml version="1.0" encoding="UTF-8"?>
<infinispan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:infinispan:config:10.0 http://www.infinispan.org/schemas/infinispan-config-10.0.xsd"
xmlns="urn:infinispan:config:10.0">
<cache-container default-cache="idempotent">
<local-cache name="idempotent">
<expiration lifespan="1800000" max-idle="1800000" interval="60000" />
<persistence passivation="true">
<file-store path="/ap/efts/data/stage/cache" purge="true">
<write-behind thread-pool-size="5" />
</file-store>
</persistence>
<memory>
<binary eviction="MEMORY" size="1000000" />
</memory>
</local-cache>
</cache-container>
</infinispan>
infinispan.xml (7.0)
<?xml version="1.0" encoding="UTF-8"?>
<infinispan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:infinispan:config:7.0 http://www.infinispan.org/schemas/infinispan-config-7.0.xsd"
xmlns="urn:infinispan:config:7.0">
<cache-container default-cache="default">
<local-cache name="idempotent">
<eviction max-entries="10000" strategy="LIRS"/>
<persistence passivation="false">
<file-store path="/ap/efts/data/stage/cache" max-entries="10000" purge="false">
</file-store>
</persistence>
</local-cache>
</cache-container>
</infinispan>
spring bean configuration
<bean id="cacheManager" class="org.infinispan.manager.DefaultCacheManager" init-method="start" destroy-method="stop">
<constructor-arg type="java.lang.String" value="infinispan.xml"/>
</bean>
<bean id="infinispanRepo" class="org.apache.camel.component.infinispan.processor.idempotent.InfinispanIdempotentRepository"
factory-method="infinispanIdempotentRepository">
<constructor-arg ref="cacheManager" />
<constructor-arg value="idempotent" />
</bean>
It is creating a file for each segment (caches internally are organized in segments). The default is 256. This makes operations such as iteration much faster.
You can disable segmentation at the store level by adding a segmented="false" attribute to the file-store element

How to fix inconsistency in Jackrabbit JCR (BundleFsPersistenceManager)

We are using JackRabbit in production. Unfortunately we have some inconsistencies in the repositories which make the data not unreadable:
ERROR ResourceServiceImpl - RepositoryException to JCR javax.jcr.PathNotFoundException: 1661b5c
The spring bean configuration looks like this:
<bean id="repository" class="org.apache.jackrabbit.core.RepositoryImpl" destroy-method="shutdown">
<constructor-arg index="0" ref="config" />
</bean>
<bean id="config" class="org.apache.jackrabbit.core.config.RepositoryConfig" factory-method="create">
<constructor-arg index="0" ref="jcrXml"/>
<constructor-arg index="1" value="${instance.repository}" />
</bean>
<bean id="jcrXml" class="com.example.misc.InputStreamBeanFactory" factory-method="createStream">
<constructor-arg value="/jackrabbit-repository.xml" />
</bean>
<bean name="jcrSession" factory-bean="repository" factory-method="login" scope="session" destroy-method="logout" />
The workspaces.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?><Workspace name="default">
<FileSystem class="org.apache.jackrabbit.core.fs.local.LocalFileSystem">
<param name="path" value="${wsp.home}"/>
</FileSystem>
<PersistenceManager class="org.apache.jackrabbit.core.persistence.bundle.BundleFsPersistenceManager"/>
</Workspace>
From what I've learned (too late) here, the above configured BundleFsPersistenceManager can become inconsistent. It is also writen here that this should NOT be used into production. Well, it is now in production and no one has noticed this before and we would like to exchange this. However first we have to migrate the data and for this reason we need to fix it.
My question: Is there a way to fix this or are these data lost for good?
My second question: What can we do to avoid these issues in the future?.
There's some notes about additional check.. params that can be set on persistence managers on Adobe CQ - Repository Inconsistency (uses Jackrabbit). The Magnolia - JCR Troubles has a script example for searching for and removing broken nodes. I've seen an approach that combined the logic from this script (written in java) and the checking params allow for a repository to be brought back up and running long enough to get the content out.
To avoid the issues in future - where you want a standalone setup that doesn't use a RDBMS - I'd suggest org.apache.jackrabbit.core.persistence.pool.DerbyPersistenceManager.
<PersistenceManager class="org.apache.jackrabbit.core.persistence.pool.DerbyPersistenceManager">
<param name="url" value="jdbc:derby:${wsp.home}/db;create=true"/>
<param name="schemaObjectPrefix" value="${wsp.name}_"/>
</PersistenceManager>

Spring data #transactional not rolling back with SQL Server and after runtimeexception

I've enabled my spring application to use transactions and annotated my service method accordingly but the changes to my DB persist when a RuntimeException is thrown.
My Spring configuration looks like this:
<!-- Data Source. -->
<jee:jndi-lookup id="dataSource" jndi-name="java:/jdbc/BeheermoduleDS"/>
<!-- JPA Entity Manager. -->
<jee:jndi-lookup id="entityManagerFactory" jndi-name="java:/jpa/BeheermoduleDS"/>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
My datasource configuration in my jboss' configuration file looks like this:
<datasource jta="true" jndi-name="java:/jdbc/BeheermoduleDS" pool-name="BeheermoduleDS" enabled="true" use-java-context="true" use-ccm="true">
<connection-url>jdbc:sqlserver://localhost:1433;databaseName=Gebruikers;</connection-url>
<driver>sqljdbc</driver>
<security>
<user-name>jboss</user-name>
<password>*****</password>
</security>
</datasource>
My Service method looks like this:
#Transactional
public void authorise(Gebruiker user) {
user.setStatus(GebruikerStatus.Actief.name());
gebruikerRepo.save(user);
if (true) {
throw new RuntimeException("Exception happened just like that");
}
// does more stuff here that is never reached
}
My repository extends a spring data repository and looks like this:
public interface GebruikerRepository extends PagingAndSortingRepository<Gebruiker, Long>, QueryDslPredicateExecutor<Gebruiker> {
}
The transaction is thrown and caught by a controller which just shows a message to the user that an exception occurred. When I check my SQL Server DB, the change made to the user status have been commited.
Weren't they supposed to have been rolled back with the RuntimeException?
After turning debug on for org.springframework.transaction.interceptor I saw that no transactions are being started for my service method, but they are for a bunch of JpaRepository methods.
Also, this is how my persistence.xml looks like:
<persistence-unit name="BeheermodulePU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>java:/jdbc/BeheermoduleDS</non-jta-data-source>
Judging from the symptoms you describe you are scanning for the same classes twice. You probably have the same <context:component-scan /> in both the configuration of the ContextLoaderListener and DispatcherServlet.
You want the ContextLoaderListener to scan for everything but #Controller and the DispatcherServlet only for #Controllers. Leading to something like this.
For the ContextLoaderListener
<!-- Load everything except #Controllers -->
<context:component-scan base-package="com.myapp">
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
For the DispatcherServlet
<!-- Load everything except #Controllers -->
<context:component-scan base-package="com.myapp" use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
See also #Service are constructed twice for another sample and broader explanation.

How to view the inserted rows when JPA testing with arquillian / hibernate?

I have an arquillian unit test that is writing a Note and passing the unit tests.
Now I would like to actually view what is being persisted into my SQLServer database.
When I open up SQLServer, I see my "Note" table, with all of the requisite columns...but there's no data.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="noteUnit"
transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/jdbc/datasources/notes</jta-data-source>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServer2005Dialect" />
<property name="hibernate.transaction.manager_lookup_class"
value="org.hibernate.transaction.JBossTransactionManagerLookup" />
<property name="hibernate.hbm2ddl.auto" value="create"/>
</properties>
</persistence-unit>
</persistence>
I've tried various values for hbm22ddl.auto--'create-drop', 'update','validate', but since my test passes, I assume that the new rows are being inserted and then immediately removed by arquillian after the unit test?
Unit test below passes--meaning arquillian's xml file and all the other assorted plumbing appears to be set up correctly. Is there a setting somewhere to save all the data that's being inserted?
private NoteEntity createNote(){
NoteEntity note = new NoteEntity();
note.setGuid("123456789");
note.setAuthorId("12345");
return note;
}
#Test
public void createNoteTest(){
NoteEntity note1 = createNote();
mEntityManager.persist(note1);
Assert.assertNotNull(note1.getId());
}
Generally, jUnit are configured so that their transaction is in defaultrollback=true mode. This is done to avoid inserting test data in your database. You will probably find the configuration over your class definition or in an extended class.
Example for jUnit with Spring IOC configuration :
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath*:myPath/spring*Context.xml")
#TransactionConfiguration(defaultRollback = true)
#Transactional
public abstract class AbstactSpringTestCase {
...
}

how to deal with datastore-indexes app engine?

for this example LINK
i try to make it but this exception occurred ??
com.google.appengine.api.datastore.DatastoreNeedIndexException: no matching index found.
The suggested index for this query is:
<datastore-index kind="Contact" ancestor="true" source="manual">
<property name="UserContacts_INTEGER_IDX" direction="asc"/>
</datastore-index>
how can i write these indexes manually ?? i try to make WEB-INF/datastore-indexes.xml
at this XML i write the following :
<?xml version="1.0" encoding="utf-8"?>
<datastore-indexes autoGenerate="true">
<datastore-index kind="Contact" ancestor="true" source="manual">
<property name="UserContacts_INTEGER_IDX" direction="asc"/>
</datastore-index>
but when Iam going to deploy this error stop me to continue deploying
An internal error occurred during: "Deploying store to Google".
XML error validating
So how can i get these indexes ??
another issues >>
when i run this code and add some properties at User class as
#Persistent (mappedBy = "userC")
public List<Contact> UserContacts =new ArrayList<Contact>();
and deploy it , the engine make indexes for the UserContacts however appear Exception due to the new property - same error above can't make indexes to them -
The best thing for you to do is run you app locally and perform some test queries on those entities.
As you have <datastore-indexes autoGenerate="true"> in your indexes config you should get a file called
WEB-INF/appengine-generated/datastore-indexes-auto.xml
in there you should get all the index definitions needed for your app to work.
Copy those index definitions to your WEB-INF/datastore-indexes.xml and update your app.
If you go to your cloud console and check on your Storage/datastore/indexes view you should be all those indexed either building or serving. Once all those indexes are on "serving" you should be good to go.

Resources