Spring Jpa Repositories - Orm.xml - jpa

I'm working with Spring Jpa Repositories.
I don't want to define my "named queries" in java classes (entities or repositories). I would like to define my "named queries" in different xml files (like orm.xml).
.... XML FILE ....
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm http://xmlns.jcp.org/xml/ns/persistence/orm_2_1.xsd">
<named-query name="MyEntity.findByField1">
<query>
<![CDATA[
SELECT m
FROM MyEntity m
WHERE
m.field1 = :field1
]]>
</query>
</named-query>
</entity-mappings>
.... REPOSITORY CODE ....
public interface MyEntityRepository extends JpaRepository<MyEntity, String>
{
public Optional<MyEntity> findByField1(#Param("field1") String field1);
}
But my repositories are not finding the xml files with my named queries. How do I configure spring-data-jpa to use these xml files? I do not have a persistence.xml.
Thanks!

Since your MyEntity already has field1 property inside using findByField1 as the Repository method name might be confusing. Change the orm.xml as following and place it inside META-INF/orm.xml
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm http://xmlns.jcp.org/xml/ns/persistence/orm_2_1.xsd">
<named-query name="MyEntity.findByField1OrmXml">
<query>
<![CDATA[
SELECT m
FROM MyEntity m
WHERE
m.field1 = :field1
]]>
</query>
</named-query>
</entity-mappings>
And change the Repository as following
public interface MyEntityRepository extends JpaRepository<MyEntity, String>
{
public Optional<MyEntity> findByField1OrmXml(#Param("field1") String field1);
}

Related

sessionContext.getCallerPrincipal().getName() returns "anonymous"

I am new to EJB.
I am using Wildfly server.
I have session stateless Ejb as below.
#Stateless(name="PrintHandler")
#RunAs("TrustedExternalModule")
public class PrintHandlerBean extends ActivityBean implements PrintHandlerLocal {
The session ejb is packed to a server-ejb.jar and that jar is packed to .ear
I have created ejb-jar.xml and jboss-ejb3.xml inside META-INF folder in server-ejb.jar as below.
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd">
<enterprise-beans>
<session>
<ejb-name>PrintHandler</ejb-name>
<security-identity>
<run-as>
<role-name>TrustedExternalModule</role-name>
</run-as>
</security-identity>
</session>
</enterprise-beans>
</ejb-jar>
<?xml version="1.1" encoding="UTF-8"?>
<jboss:ejb-jar xmlns:jboss="http://www.jboss.com/xml/ns/javaee"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:s="urn:security:1.1"
xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee http://www.jboss.org/j2ee/schema/jboss-ejb3-2_0.xsd http://java.sun.com/xml/ns/javaee http://www.jboss.org/j2ee/schema/jboss-ejb3-spec-2_0.xsd"
version="3.1"
impl-version="2.0">
<jboss:enterprise-beans>
<session>
<ejb-name>PrintHandler</ejb-name>
<session-type>Stateless</session-type>
<security-identity>
<run-as>
<role-name>TrustedExternalModule</role-name>
</run-as>
</security-identity>
</session>
</jboss:enterprise-beans>
<assembly-descriptor>
<s:security>
<ejb-name>PrintHandler</ejb-name>
<s:security-domain>other</s:security-domain>
<s:run-as-principal>TESTCONNECT</s:run-as-principal>
</s:security>
</assembly-descriptor>
</jboss:ejb-jar>
I am injecting SessionContext annotated with Resource in a non ejb class as below.
public abstract class AbstractBean {
protected AbstractBean() {
log = LogMgr.getFrameworkLogger();
clsLog = LogMgr.getClassLogger(FndAbstractBean.class);
if(clsLog.debug) {
clsLog.debug("Created bean [&1]", getClass().getName());
}
}
**#Resource
protected SessionContext sessionContext;**
But when I am calling String user = sessionContext.getCallerPrincipal().getName();
it is returning "anonymous" always.
How can I solve this.
I want to get caller principal as TESTCONNECT.
Hello, this seems to be an expected behavior. The only workaround I found would be to use Interceptor,so then you can propagate the information actually. Interceptors is explained here

JPA not generating ddl files

I'm setting up a JavaEE Webapplication and want to generate ddl files so I can see what they look like
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence"
version="2.1">
<persistence-unit name="contentAggregatorPU">
<class>contentAggregator.model.Item</class>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.schema-generation.scripts.action" value="drop-and-create"/>
<property name="javax.persistence.schema-generation.scripts.create-target" value="contentAggregatorCreate.ddl"/>
<property name="javax.persistence.schema-generation.scripts.drop-target" value="contentAggregatorDrop.ddl"/>
</properties>
</persistence-unit>
</persistence>
It just does not generate the files.
Honestly I never used the mechanism. While it seems to work for my local-resource minimal JPA playground it gave me errors when attempting to deploy to wildfly. I've always used a small utility class for generating a schema.
public class SchemaTranslator {
public static void main(String[] args) throws IOException {
Class<?>[] entityClasses = {
Class1.class,
Class2.class,
};
MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder()
.applySetting("hibernate.hbm2ddl.auto", "create")
.applySetting("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect")
// .applySetting("hibernate.physical_naming_strategy", "package.MyImprovedNamingStrategy")
.build()
);
// [...] adding annotated classes to metadata here...
for (Class<?> clazz : entityClasses)
metadata.addAnnotatedClass(clazz);
EnumSet<TargetType> targetTypes = EnumSet.of(TargetType.STDOUT, TargetType.SCRIPT);
SchemaExport export = new SchemaExport()
// .setHaltOnError( haltOnError )
.setOutputFile("db-schema.sql")
.setDelimiter(";");
export.create(targetTypes, (MetadataImplementor) metadata.buildMetadata());
}
}

EntityManager in JNDI

I need to use different databases in the same Web application, so I can't use a persistent.xml to define the target database. The database changes with the client which is connected.
I found this :
public EntityManager getEntityManager() {
if (em == null}
try{
em = (EntityManager)(new InitialContext())
.lookup("java:comp/ejb/EntityManager");
} catch (Exception e){};
}
return em;
}
at this URL : http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI
My question is now : how recording a EntityManager or a Persistence Unit in the JNDI of GlassFish ?
Suppose that my persistence.xml is:
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="ctx-vendor" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
</persistence-unit>
</persistence>
We have two use case:
WAR application WEB-INF/web.xml file:
<persistence-context-ref>
<description>JNDI for lookup EntityManager</description>
<persistence-context-ref-name>persistence/ctx-vendor</persistence-context-ref-name>
<persistence-unit-name>ctx-vendor</persistence-unit-name>
<persistence-context-type>Transaction</persistence-context-type>
</persistence-context-ref>
EAR application META-INF/application.xml file:
<application xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/application_7.xsd"
version="7">
<description>My Vendor System</description>
<display-name>vendor-ear</display-name>
<module>
<web>
<web-uri>vendor-rest.war</web-uri>
<context-root>/vendor-rest</context-root>
</web>
</module>
<module>
<ejb>vendor-service.jar</ejb>
</module>
<library-directory>lib</library-directory>
<persistence-context-ref>
<description>JNDI for lookup EntityManager</description>
<persistence-context-ref-name>persistence/ctx-vendor</persistence-context-ref-name>
<persistence-unit-name>ctx-vendor</persistence-unit-name>
<persistence-context-type>Transaction</persistence-context-type>
</persistence-context-ref>
</application>
Stateless Session Bean
#PersistenceContext(name = "persistence/ctx-vendor", unitName = "ctx-vendor")
public class BaseFacade
{ }
#Stateless
#Local(CatalogFacade.class)
public class CatalogFacadeImpl extends BaseFacade implements CatalogFacade
{
}
Tested in Glassfish 4.1

camel jpa waiting for namespace handlers

I'm trying to write a RouteTest class for my camel jpa example and it does not work as expected because of the following line :
Bundle RouteTest is waiting for namespace handlers [http://aries.apache.org/xmlns/jpa/v1.1.0]
Please find here blueprint.xml file
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:camel="http://camel.apache.org/schema/blueprint"
xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0"
xmlns:jpa="http://aries.apache.org/xmlns/jpa/v1.1.0"
xsi:schemaLocation="
http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd
http://aries.apache.org/xmlns/jpa/v1.1.0 http://aries.apache.org/schemas/jpa/jpa_110.xsd">
<bean id="jpa" class="org.apache.camel.component.jpa.JpaComponent">
<jpa:unit unitname="persistence-pu" property="entityManagerFactory" />
</bean>
<camelContext trace="true" id="blueprintContext" xmlns="http://camel.apache.org/schema/blueprint">
<route id="persist">
<from uri="direct:persist"/>
<to uri="jpa:Person"/>
</route>
</camelContext>
</blueprint>
and here RouteTest class :
public class RouteTest extends CamelBlueprintTestSupport {
#Override
protected String getBlueprintDescriptor() {
return "/OSGI-INF/blueprint/blueprint.xml";
}
#Test
public void testRoute() throws Exception {
getMockEndpoint("mock:result").expectedMinimumMessageCount(1);
ProducerTemplate producerTemplate = new DefaultCamelContext().createProducerTemplate();
Person person = new Person();
person.setName("Bob");
producerTemplate.sendBody("direct:persist", person);
// assert expectations
assertMockEndpointsSatisfied();
}
}
you need to provide Aries Blueprint, and especially you need to provide the aries JPA dependencies. How do you Test your Routes? I'd suggest using Pax-Exam or probably better to use Pax-Exam-Karaf and intall the aries jpa features.

How to change the preferences so that each window displays something different?

I'm trying to override values of preferences, but nothing overrides.
Does anyone know how to fix this?
portlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd">
<portlet>
<portlet-name>cool_portlet</portlet-name>
<portlet-class>org.springframework.web.portlet.DispatcherPortlet</portlet-class>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
</supports>
<supported-locale>en</supported-locale>
<resource-bundle>com.app.portlet.cool_portlet</resource-bundle>
<portlet-info>
<title>Cool Portlet</title>
</portlet-info>
<portlet-preferences>
<preference>
<name>KEY</name>
<value>TEST</value>
<read-only>false</read-only>
</preference>
</portlet-preferences>
</portlet>
</portlet-app>
portlet-instances.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE deployments PUBLIC "-//JBoss Portal//DTD Portlet Instances 2.6//EN" "http://www.jboss.org/portal/dtd/portlet-instances_2_6.dtd">
<deployments>
<deployment>
<instance>
<instance-id>coolPortlet_IMPORT_newInstance</instance-id>
<portlet-ref>cool_portlet</portlet-ref>
<preferences>
<name>KEY</name>
<value>IMPORT</value>
</preferences>
</instance>
</deployment>
<deployment>
<instance>
<instance-id>coolPortlet_EXPORT_newInstance</instance-id>
<portlet-ref>cool_portlet</portlet-ref>
<preferences>
<name>KEY</name>
<value>EXPORT</value>
</preferences>
</instance>
</deployment>
</deployments>
cool_portlet-object.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE deployments PUBLIC "-//JBoss Portal//DTD Portlet Instances 2.6//EN" "http://www.jboss.org/portal/dtd/portlet-instances_2_6.dtd">
<deployments>
<deployment>
<parent-ref>comportal.import</parent-ref>
<if-exists>overwrite</if-exists>
<window>
<window-name>impWindow</window-name>
<content>
<content-type>portlet</content-type>
<content-uri>coolPortlet_IMPORT_newInstance</content-uri>
</content>
<region>center</region>
<height>1</height>
<supported-window-states>
<window-state>normal</window-state>
<window-state>maximized</window-state>
<window-state>minimized</window-state>
</supported-window-states>
<initial-window-state>normal</initial-window-state>
</window>
</deployment>
<deployment>
<parent-ref>comportal.export</parent-ref>
<if-exists>overwrite</if-exists>
<window>
<window-name>expWindow</window-name>
<content>
<content-type>portlet</content-type>
<content-uri>coolPortlet_EXPORT_newInstance</content-uri>
</content>
<region>center</region>
<height>1</height>
<supported-window-states>
<window-state>normal</window-state>
<window-state>maximized</window-state>
<window-state>minimized</window-state>
</supported-window-states>
<initial-window-state>normal</initial-window-state>
</window>
</deployment>
</deployments>
MainController.java
#RequestMapping(value = "VIEW")
#Controller(value = "mainController")
public class MainController {
#RenderMapping
public String init(#RequestParam(value = "key", required = false) String key, Model model, PortletRequest request) throws Exception {
PortletPreferences preferences = request.getPreferences();
String preferencesKey = preferences.getValue("KEY", "Not Found!!!");
System.out.println("KEY is : " + preferencesKey);
model.addAttribute("preferencesKey", preferencesKey);
return "index";
}
}
Output:
13:49:54,860 INFO [STDOUT] KEY is : TEST
13:50:21,088 INFO [STDOUT] KEY is : TEST
You need to call setValue and then store your PortletPreferences object. Note that preferences can only be stored in action phase. visit