Search Results

Search found 49 results on 2 pages for 'jpql'.

Page 2/2 | < Previous Page | 1 2 

  • Deleting orphans with JPA

    - by homaxto
    I have a one-to-one relation where I use CascadeType.PERSIST. This has over time build up a huge amount of child records that has not been deleted, to such an extend that it is reflected in the performance. Now I wish to add some code that cleans up the database removing all the child records that are not referenced by a parent. At the moment we are talking 400K+ records, at I need to run the code on all customer installations just to be sure they do not run into the same problem. I think the best solution would be to run a named query (because we support two databases) that deletes the necessary records, and this is where I get into problems, because how should I write it in JPQL? The result I want can be defined like the following sql statement, which unfortunaltely does not run on MySQL. DELETE FROM child c1 WHERE c1.pk NOT IN (SELECT DISTINCT p.pk FROM child c2 JOIN parent p ON p.child = c2.pk);

    Read the article

  • Is this possible: JPA/Hibernate query with list property in result ?

    - by Kdeveloper
    In hibernate I want to run this JPQL / HQL query: select new org.test.userDTO( u.id, u.name, u.securityRoles) FROM User u WHERE u.name = :name userDTO class: public class UserDTO { private Integer id; private String name; private List<SecurityRole> securityRoles; public UserDTO(Integer id, String name, List<SecurityRole> securityRoles) { this.id = id; this.name = name; this.securityRoles = securityRoles; } ...getters and setters... } User Entity: @Entity public class User { @id private Integer id; private String name; @ManyToMany @JoinTable(name = "user_has_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = {@JoinColumn(name = "security_role_id") } ) private List<SecurityRole> securityRoles; ...getters and setters... } But when Hibernate 3.5 (JPA 2) starts I get this error: org.hibernate.hql.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [org.test.UserDTO] [SELECT NEW org.test.UserDTO (u.id, u.name, u.securityRoles) FROM nl.test.User u WHERE u.name = :name ] Is a select that includes a list as a result not possible? Should I just create 2 seperate queries?

    Read the article

  • Displaying data from linked tables in netbeans JTable

    - by Darc
    I have been writing in java for a few months now and have just started using netbeans. I have spent all day today trying to work out how to connect to an SQL database and display data from 2 tables (ie display the data from from a select statement with an inner join) in a JTable. I have tried using JPQL with the following statment SELECT j, cust.name FROM Job j JOIN j.jobnumber cust where the job table has a field called customer that references id in the customer table. This throws the exception: Caused by: Exception [TOPLINK-8029] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EJBQLException Exception Description: Error compiling the query [SELECT j, cust.name FROM Job j JOIN j.jobnumber cust], line 1, column 11: invalid navigation expression [cust.name], cannot navigate expression [cust] of type [java.lang.Integer] inside a query. at oracle.toplink.essentials.exceptions.EJBQLException.invalidNavigation(EJBQLException.java:430) What am i doing wrong? Can anyone point me to some examples of how to make a linked table java application? I am still in the very early stages of development so a complete change is not out of the question if using a mysql database isnt the best way to go about things thanks

    Read the article

  • Using the JPA Criteria API, can you do a fetch join that results in only one join?

    - by Shaun
    Using JPA 2.0. It seems that by default (no explicit fetch), @OneToOne(fetch = FetchType.EAGER) fields are fetched in 1 + N queries, where N is the number of results containing an Entity that defines the relationship to a distinct related entity. Using the Criteria API, I might try to avoid that as follows: CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<MyEntity> query = builder.createQuery(MyEntity.class); Root<MyEntity> root = query.from(MyEntity.class); Join<MyEntity, RelatedEntity> join = root.join("relatedEntity"); root.fetch("relatedEntity"); query.select(root).where(builder.equals(join.get("id"), 3)); The above should ideally be equivalent to the following: SELECT m FROM MyEntity m JOIN FETCH myEntity.relatedEntity r WHERE r.id = 3 However, the criteria query results in the root table needlessly being joined to the related entity table twice; once for the fetch, and once for the where predicate. The resulting SQL looks something like this: SELECT myentity.id, myentity.attribute, relatedentity2.id, relatedentity2.attribute FROM my_entity myentity INNER JOIN related_entity relatedentity1 ON myentity.related_id = relatedentity1.id INNER JOIN related_entity relatedentity2 ON myentity.related_id = relatedentity2.id WHERE relatedentity1.id = 3 Alas, if I only do the fetch, then I don't have an expression to use in the where clause. Am I missing something, or is this a limitation of the Criteria API? If it's the latter, is this being remedied in JPA 2.1 or are there any vendor-specific enhancements? Otherwise, it seems better to just give up compile-time type checking (I realize my example doesn't use the metamodel) and use dynamic JPQL TypedQueries.

    Read the article

  • Filter entities that match all pairs

    - by Jon
    I have an entity (let's say Person) with a set of arbitrary attributes with a known subset of values. I need to search for all of these entities that match all my filter conditions. For example, my table structures look like this: Person: id | name 1 | John Doe 2 | Jane Roe 3 | John Smith Attribute: id | attr_name 1 | Sex 2 | Eye Color ValidValue: id | attr_id | value_name 1 | 1 | Male 2 | 1 | Female 3 | 2 | Blue 4 | 2 | Green 5 | 2 | Brown PersonAttributes id | person_id | attr_id | value_id 1 | 1 | 1 | 1 2 | 1 | 2 | 3 3 | 2 | 1 | 2 4 | 2 | 2 | 4 5 | 3 | 1 | 1 6 | 3 | 2 | 4 In JPA, I have entities built for all of these tables. What I'd like to do is perform a search for all entities matching a given set of attribute-value pairs. For instance, I'd like to be able to find all males (John Doe and John Smith), all people with green eyes (Jane Roe or John Smith), or all females with green eyes (Jane Roe). I see that I can already take advantage of the fact that I only really need to match on value_id, since that's already unique and tied to the attr_id. But where can I go from there?

    Read the article

  • Match entities fulfilling filter (strict superset of search)

    - by Jon
    I have an entity (let's say Person) with a set of arbitrary attributes with a known subset of values. I need to search for all of these entities that match all my filter conditions. That is, given a set of Attributes A, I need to find all people that have a set of Attributes that are a superset of A. For example, my table structures look like this: Person: id | name 1 | John Doe 2 | Jane Roe 3 | John Smith Attribute: id | attr_name 1 | Sex 2 | Eye Color ValidValue: id | attr_id | value_name 1 | 1 | Male 2 | 1 | Female 3 | 2 | Blue 4 | 2 | Green 5 | 2 | Brown PersonAttributes id | person_id | attr_id | value_id 1 | 1 | 1 | 1 2 | 1 | 2 | 3 3 | 2 | 1 | 2 4 | 2 | 2 | 4 5 | 3 | 1 | 1 6 | 3 | 2 | 4 In JPA, I have entities built for all of these tables. What I'd like to do is perform a search for all entities matching a given set of attribute-value pairs. For instance, I'd like to be able to find all males (John Doe and John Smith), all people with green eyes (Jane Roe or John Smith), or all females with green eyes (Jane Roe). I see that I can already take advantage of the fact that I only really need to match on value_id, since that's already unique and tied to the attr_id. But where can I go from there? I've been trying to do something like the following, given that the ValidValue is unique in all cases: select distinct p from Person p join p.personAttributes a where a.value IN (:values) Then I've tried putting my set of required values in as "values", but that gives me errors no matter how I try to structure that. I also have to get a little more complicated, as follows, but at this point I'd be happy with solving the first problem cleanly. However, if it's possible, the Attribute table actually has a field for default value: id | attr_name | default_value 1 | Sex | 1 2 | Eye Color | 5 If the value you're searching on happens to be the default value, I want it to return any people that have no explicit value set for that attribute, because in the application logic, that means they inherit the default value. Again, I'm more concerned about the primary question, but if someone who can help with that also has some idea of how to do this one, I'd be extremely grateful.

    Read the article

  • JPA optimistic lock - setting @Version to entity class cause query to include VERSION as column

    - by masato-san
    I'm using JPA Toplink Essential, Netbean6.8, GlassFish v3 In my Entity class I added @Version annotation to enable optimistic locking at transaction commit however after I added the annotation, my query started including VERSION as column thus throwing SQL exception. None of this is mentioned in any tutorial I've seen so far. What could be wrong? Snippet public class MasatosanTest2 implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "id") private Integer id; @Column(name = "username") private String username; @Column(name = "note") private String note; //here adding Version @Version int version; query used: SELECT m FROM MasatosanTest2 m Internal Exception: com.microsoft.sqlserver.jdbc.SQLServerException Call: SELECT id, username, note, VERSION FROM MasatosanTest2

    Read the article

  • Setting a parameter as a list for an IN expression

    - by perilandmishap
    Whenever I try to set a list as a parameter for use in an IN expression I get an Illegal argument exception. Various posts on the internet seem to indicate that this is possible, but it's certainly not working for me. I'm using Glassfish V2.1 with Toplink. Has anyone else been able to get this to work, if so how? here's some example code: List<String> logins = em.createQuery("SELECT a.accountManager.loginName " + "FROM Account a " + "WHERE a.id IN (:ids)") .setParameter("ids",Arrays.asList(new Long(1000100), new Long(1000110))) .getResultList(); and the relevant part of the stack trace: java.lang.IllegalArgumentException: You have attempted to set a value of type class java.util.Arrays$ArrayList for parameter accountIds with expected type of class java.lang.Long from query string SELECT a.accountManager.loginName FROM Account a WHERE a.id IN (:accountIds). at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.setParameterInternal(EJBQueryImpl.java:663) at oracle.toplink.essentials.internal.ejb.cmp3.EJBQueryImpl.setParameter(EJBQueryImpl.java:202) at com.corenap.newtDAO.ContactDaoBean.getNotificationAddresses(ContactDaoBean.java:437) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.sun.enterprise.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1011) at com.sun.enterprise.security.SecurityUtil.invoke(SecurityUtil.java:175) at com.sun.ejb.containers.BaseContainer.invokeTargetBeanMethod(BaseContainer.java:2920) at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4011) at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:203) ... 67 more

    Read the article

  • JPA + EJB + JSF: how can design complicated query

    - by Harry Pham
    I am using netbean 6.8 btw. Let say that I have 4 different tables: Company, Facility, Project, and Document. So the relationship is this. A company can have multiple facilities. A facility can have multiple projects, and a project can have multiple documents. Company: +companyNum: PK +facilityNum: FK Facility: +facilityNum: PK +projectNum: FK Project: +projectNum: PK +drawingNum: FK So when I create Entity Class From Database in netbean 6.8, I have 4 entity classes that named after the above 4 tables. So if I want to see all the Document in the database, then it is easy. In my SessionBean, I would do this: @PersistenceContext private EntityManager em; List<Document> documents = em.createNamedQuery("Document.findAll").getResultList(); However, that is not all what I need. Let say that I want to know all the Document from a particular Company, or all the Document from a particular Project from a particular Facility from a particular Company. I am very new to JPA + EJB + JSF as a whole. Please help me out.

    Read the article

  • How to backup database to disk using JPA?

    - by Nitesh Panchal
    Hello, Which query to write in JPQL for backing up database on disk? If in JPQL it's not available even native sql query will do. Also, i would like to bring one issue in front of stackoverflow developers :- This site doesn't properly work in Opera (Opera 9.63). Whenever i write question and click "Post Your question" The button click event doesn't fire at all, may be, the server side event doesn't fire or something. However, no such problem comes in IE and firefox.

    Read the article

  • Exception in inserting data into data using JPA in netbeans

    - by sandeep
    SEVERE: Local Exception Stack: Exception [EclipseLink-7092] (Eclipse Persistence Services - 2.0.0.v20091127-r5931): org.eclipse.persistence.exceptions.ValidationException Exception Description: Cannot add a query whose types conflict with an existing query. Query To Be Added: [ReadAllQuery(name="Voter.findAll" referenceClass=Voter jpql="SELECT v FROM Voter v")] is named: [Voter.findAll] with arguments [[]].The existing conflicting query: [ReadAllQuery(name="Voter.findAll" referenceClass=Voter jpql="SELECT v FROM Voter v")] is named: [Voter.findAll] with arguments: [[]].

    Read the article

  • Error in inserting data into data using JPA in netbeans

    - by sandeep
    SEVERE: Local Exception Stack: Exception [EclipseLink-7092] (Eclipse Persistence Services - 2.0.0.v20091127-r5931): org.eclipse.persistence.exceptions.ValidationException Exception Description: Cannot add a query whose types conflict with an existing query. Query To Be Added: [ReadAllQuery(name="Voter.findAll" referenceClass=Voter jpql="SELECT v FROM Voter v")] is named: [Voter.findAll] with arguments [[]].The existing conflicting query: [ReadAllQuery(name="Voter.findAll" referenceClass=Voter jpql="SELECT v FROM Voter v")] is named: [Voter.findAll] with arguments: [[]].

    Read the article

  • GoogleAppEngine : ClassNotFoundException : javax.jdo.metadata.ComponentMetadata

    - by James.Elsey
    I'm trying to deploy my application to a locally running GoogleAppEngine development server, but I'm getting the following stack trace when I start the server Apr 23, 2010 9:03:33 PM com.google.apphosting.utils.jetty.JettyLogger warn WARNING: Nested in org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientDao' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/jdo/metadata/ComponentMetadata: java.lang.ClassNotFoundException: javax.jdo.metadata.ComponentMetadata at java.net.URLClassLoader$1.run(URLClassLoader.java:217) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:205) at java.lang.ClassLoader.loadClass(ClassLoader.java:319) at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:151) at java.lang.ClassLoader.loadClass(ClassLoader.java:264) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:332) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:264) at javax.jdo.JDOHelper$18.run(JDOHelper.java:2009) at javax.jdo.JDOHelper$18.run(JDOHelper.java:2007) at java.security.AccessController.doPrivileged(Native Method) at javax.jdo.JDOHelper.forName(JDOHelper.java:2006) at javax.jdo.JDOHelper.invokeGetPersistenceManagerFactoryOnImplementation(JDOHelper.java:1155) at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:803) at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:698) at org.datanucleus.jpa.EntityManagerFactoryImpl.initialisePMF(EntityManagerFactoryImpl.java:482) at org.datanucleus.jpa.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:255) at org.datanucleus.store.appengine.jpa.DatastoreEntityManagerFactory.<init>(DatastoreEntityManagerFactory.java:68) at org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider.createContainerEntityManagerFactory(DatastorePersistenceProvider.java:45) at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:224) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:291) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:269) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1245) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:530) at org.mortbay.jetty.servlet.Context.startContext(Context.java:135) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1218) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:500) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:448) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:117) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:117) at org.mortbay.jetty.Server.doStart(Server.java:217) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:181) at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:116) at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:217) at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:162) at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:48) at com.google.appengine.tools.development.DevAppServerMain.<init>(DevAppServerMain.java:113) at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:89) The server is running at http://localhost:1234/ I'm a little confused over this, since I have the same application running locally on GlassFish/MySQL. All I have done is to swap in the relevant jar files, and change the persistence.xml. My applicationContext.xml looks as follows : <context:annotation-config/> <bean id="clientDao" class="com.jameselsey.salestracker.dao.jpa.JpaDaoClient"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"/> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean id="org.springframework.context.annotation.internalPersistenceAnnotationProcessor" class="com.jameselsey.salestracker.util.GaeFixInternalPersistenceAnnotationProcessor" /> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> <tx:annotation-driven/> <bean id="clientService" class="com.jameselsey.salestracker.service.ClientService"/> </beans> My JPA DAO looks like this public class JpaDao extends JpaDaoSupport { protected <T> List<T> findAll(Class<T> clazz) { return getJpaTemplate().find("select c from " + clazz.getName() + " c"); } protected <T> T findOne(String jpql, Map params) { List<T> results = getJpaTemplate().findByNamedParams(jpql, params); if(results.isEmpty()) { return null; } if(results.size() > 1) { throw new IncorrectResultSizeDataAccessException(1, results.size()); } return results.get(0); } } And an example implemented method looks like this : @Override public Client getClientById(Integer clientId) { String jpql = "SELECT c " + "FROM com.jameselsey.salestracker.domain.Client c " + "WHERE c.id = " + clientId; return (Client) getJpaTemplate().find(jpql).get(0); } Like I say, this works ok on Glassfish/MySQL, is it possible this error could be a red herring to something else?

    Read the article

  • JPA 2?EJB 3.1?JSF 2????????! WebLogic Server 12c?????????Java EE 6??????|WebLogic Channel|??????

    - by ???02
    2012?2???????????????WebLogic Server 12c?????????Java EE 6?????????????????????????????????????????????????????????????Oracle Enterprise Pack for Eclipse 12c??WebLogic Server 12c(???)????Java EE 6??????3??????????????????????????????JPA 2.0??????????·?????????EJB 3.1???????·???????????????(???)???????O/R?????????????JPA 2.0 Java EE 6????????????????????Web?????????????3?????(3????)???????·????????????·????????????????????????????????JPA(Java Persistence API) 2.0???EJB(Enterprise JavaBeans) 3.1???JSF(JavaServer Faces) 2.0????3????????????????·???????????JPA??Java??????????????·?????????????O/R?????????????????????·???????????EJB?Session Bean??????????????????·??????????????????????JSF??????????????????????????????????????? ??????JPA????Oracle Database??EMPLOYEES?????Java??????????????????????Entity Bean??????XML?????????????????????????XML????????????????????????????????????????????????????·?????????????????????????????????????????????????????????????Java EE 6??????JPA 2.0??????????·???????????????????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????????Oracle Enterprise Pack for Eclipse(OEPE)??????File????????New?-?Other??????? ??????New??????????????????????????Web?-?Dynamic Web Project???????Next????????????????Dynamic Web Project?????????????Project name????OOW???????????Target Runtime????New Runtime????????? ???New Server Runtime Environment???????????????Oracle?-?Oracle WebLogic Server 12c(12.1.1)???????Next???????????????????????????WebLogic home????C:\Oracle\Middleware\wlserver_12.1???????Finish?????????????WebLogic Home????????????????????????Java home?????????????????????Finish??????????????????????Dynamic Web Project????????????????Finish??????????????????JPA 2.0??????????·?????? ???????????????JPA 2.0???????????????·??????????????????Eclipse??Project Explorer?(??????·???)?????????OOW?????????????????????????????·???????????????Properties?????????????????·???·????????????????????????????Project Facets?????????????JPA??????(?????????????Details?????JPA 2.0?????????????????????)???????????????????Further configuration available????????? ???Modify Faceted Project??????????????????????????????????Connection????????????????????????????Add Connection????????? ??????New Connection Profile????????????????Connection Profile Type????Oracle Database Connection??????Next???????????? ???Specify a Driver and Connection Details???????Drivers????Oracle Database 10g Driver Default???????????Properties?????????????????????SIDxeHostlocalhostPort number1521User nameHRPasswordhr ???????????Test Connection??????????????????Ping Succeeded!?????????????????????????????Finish???????????Modify Faceted Project????????OK????????????????Properties for OOW????????OK?????????????????? ?????????Eclipse????????????????OOW?????????????????·???????????????JPA Tools?-?Generate Entities from Tables...??????? ????Generate Custom Entities???????????????????????????????Schema????HR??????Tables????EMPLOYEES???????????Next???????????? ???????????Next???????????Customize Default Entity Generation??????Package????model???????Finish?????????????JPQL?????????? ?????????Oracle Database??EMPLOYEES??????????????????·????model.Employee.java?????????????????????????????????·?????OOW????Java Resources?-?src?-?model???????Employee.java????????????????????????????????·???Employee????(Employee.java)?package model; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.Set; import javax.persistence.Column;<...?...>/**  * The persistent class for the EMPLOYEES database table.  *  */ @Entity  // ?@Table(name="EMPLOYEES")  // ?// Apublic class Employee implements Serializable {        private static final long serialVersionUID = 1L;       @Id  // ?       @Column(name="EMPLOYEE_ID")        private long employeeId;        @Column(name="COMMISSION_PCT")        private BigDecimal commissionPct;        @Column(name="DEPARTMENT_ID")        private BigDecimal departmentId;        private String email;        @Column(name="FIRST_NAME")        private String firstName;       @Temporal( TemporalType.DATE)  //?       @Column(name="HIRE_DATE")        private Date hireDate;        @Column(name="JOB_ID")        private String jobId;        @Column(name="LAST_NAME")        private String lastName;        @Column(name="PHONE_NUMBER")        private String phoneNumber;        private BigDecimal salary;        //bi-directional many-to-one association to Employee<...?...>}  ???????????????·???????????????????????????????????????????@Table(name="")??????@Table??????????????????????????????????????? ?????????????????????????????????????·???????????????? ?????????????????????????????SQL?Data?????????? ???????????????A?????JPA?????????JPQL(Java Persistence Query Language)?????????????JPQL?????SQL???????????????????????????????????????????????????????????????????????????????????Employee.selectByNameEmployee??firstName????????????????????employeeId????????? ?????????????????????import java.util.Date;import java.util.Set;import javax.persistence.Column;<...?...>/**  * The persistent class for the EMPLOYEES database table.  *  */ @Entity  // ?@Table(name="EMPLOYEES")  // ?@NamedQueries({       @NamedQuery(name="Employee.selectByName" , query="select e from Employee e where e.firstName like :name order by e.employeeId")})<...?...> ?????????·??????OOW?-?JPA Content?-?persistent.xml??????Connection???????????????Database????JTA data source:???jdbc/test????????????????????????Java EE 6??????JPA 2.0???????????????????????????????????·??????????????????????????????????????SQL????????????????????????·????????????·??????????????XML??????????????????1??????????????????????????????????????????????????????????????????EJB 3.1????????·???????????EJB 3.1????????·?????????????????EJB 3.1?Stateless Session Bean?????·????????????????·???????????????????·??????????????????? EJB3.1?????JPA 2.0???????????·???????????????????????XML???????????????????????????????EJB 3.1?????????·????EJB?????????????????????????????????????????????????????????????? ????????EJB 3.1?Session Bean?????·????????????????????????????????????????????????????public List<Employee> getEmp(String keyword)firstName????????????Employee?????? ????????????????????·???????????OOW????????????·???????????????New?-?Other???????????????????????????????????EJB?-?Session Bean(EJB 3.x)??????NEXT????????????????????Create EJB 3.x Session Bean?????????????Java Package????ejb???class name????EmpLogic???????????State Type????Stateless?????????No-interface???????????????????????Finish???????????? ?????????Stateless Session Bean??????·?????EmpLogic.java????????????????????EmpLogic????·????????EJB?????????????Stateless Session Bean?????????@Stateless?????????????????????????????????????EmpLogic????(EmpLogic.java)?package ejb;import javax.ejb.LocalBean;import javax.ejb.Stateless;<...?...>import model.Employee;@Stateless@LocalBeanpublic class EmpLogic {       public EmpLogic() {       }} ??????????????????????????????????????·???????????????????????import??????????????????EmpLogic??????????????????????????·???????????????????????import????????(EmpLogic.java)?package ejb;import javax.ejb.LocalBean;import javax.ejb.Stateless;import javax.persistence.EntityManager;  // ?import javax.persistence.PersistenceContext;  // ?<...?...>import model.Employee;@Stateless@LocalBeanpublic class EmpLogic {      @PersistenceContext(unitName = "OOW")  // ?      private EntityManager em;  // ?       public EmpLogic() {       }} ?????????·???????JPA???????????????????·????????????????????????????CRUD???????????????????·????????????EntityManager???????????????????????????1????????????????·???????????????????????@PersistenceContext?????unitName?????????????persistence.xml????persistence-unit???name?????????????? ???????EmpLogic?????·???????????????????????????????????????????????????????????????????????????????EmpLogic????????·???????(EmpLogic.java)?package ejb;import java.util.List;  // ? import javax.ejb.LocalBean;import javax.ejb.Stateless;import javax.persistence.EntityManager;  // ? import javax.persistence.PersistenceContext;  // ? <...?...>import model.Employee;@Stateless@LocalBeanpublic class EmpLogic {       @PersistenceContext(unitName = "OOW")  // ?        private EntityManager em;  // ?        public EmpLogic() {       }      @SuppressWarnings("unchecked")  // ?      public List<Employee> getEmp(String keyword) {  // ?             StringBuilder param = new StringBuilder();  // ?             param.append("%");  // ?             param.append(keyword);  // ?             param.append("%");  // ?             return em.createNamedQuery("Employee.selectByName")  // ?                    .setParameter("name", param.toString()).getResultList();  // ?      }} ???EJB 3.1???Stateless Session Bean?????????? ???JSF 2.0???????????????????????????????????????????????????JAX-RS????RESTful?Web??????????????????????

    Read the article

  • JPA and NoSQL using EclipseLink - MongoDB supported

    - by arungupta
    EclipseLink 2.4 has added JPA support for NoSQL databases, MongoDB and Oracle NoSQL are the first ones to make the cut. The support to other NoSQL database can be extended by adding a EclipseLink EISPlatform class and a JCA adapter. A Java class can be mapped to a NoSQL datasource using the @NoSQL annotation or <no-sql> XML element. Even a subset of JPQL and the Criteria API are supported, dependent on the NoSQL database's query support. The connection properties are specified in "persistence.xml". A complete sample showing how JPA annotations are mapping and using @NoSQL is explained here. The MongoDB-version of the source code can also be checked out from the SVN repository. EclipseLink 2.4 is scheduled to be released with Eclipse Juno in June 2012 and the complete set of supported features is described on their wiki. The milestone and nightly builds are already available. Do you want to try with GlassFish and let us know ?

    Read the article

  • Java EE 7 support in NetBeans 7.3.1

    - by arungupta
    NetBeans IDE provide tools, templates, and samples for building Java EE 7 applications. NetBeans 7.3.1 specifically added support for the features mentioned below: Support for creating Java EE 7 projects using Maven and Ant Develop, Deploy, and Debug using GlassFish 4 Bundled Java EE 7 javadocs CDI is enabled by default for new Java EE 7 projects (CDI 1.1) Create database scripts from Entity Classes (JPA 2.1) Java Persistence Query Language (JPQL) testing tool (JPA 2.1) RESTful Java client creation using JAX-RS 2.0 Client APIs (JAX-RS 2.0) New templates for JAX-RS 2 Filter and Interceptor (JAX-RS 2.0) New templates for WebSocket endpoints (WebSocket 1.0) JMS messages are sent using JMS 2 simplified API (JMS 2.0) Pass-through attributes are supported during Facelet page editing (JSF 2.2) Resource Library Contracts(JSF 2.2) @FlowScoped beans from editor and wizards (JSF 2.2) Support for EL 3.0 syntax in editor (EL 3.0) JSON APIs can be used with code completion (JSON 1.0) A comprehensive list of features added in this release is available in NetBeans 7.3.1 New and Noteworthy. Watch the screencast below to get a quick overview of the features and capabilities: Download Netbeans 7.3.1 and start playing with Java EE 7!

    Read the article

  • Hibernate ResultTransformer with JPA API

    - by Timo Westkämper
    Has anyone figured out a smart way to do query result transformation through a similar mechanism like specifying a ResultTransformer in Hibernate? All I can think of is transforming each result row after it has been returned by the Query. Is there any other way? For constructor projections (e.g. new DTO(arg1, arg2)) it can be defined in the JPQL query, at least for Hibernate, but how about other cases?

    Read the article

  • Would You Swim Laps in Lake Baikal?

    - by rickramsey
    source This is the lake where Yuli Vasiliev's countrymen swim laps. Yuli is one of my favorite OTN writers not just because he really knows his stuff. Not just because his writing is clear and accurate. And not just because his English is better than the English of most native speakers. Yo, those are all good reasons. But it's the Lake Baikal thing. Yuli recently wrote two wicked good how-to's about Oracle VM Templates. You should read them. You might gain a gram of Yuli's respect. Two grams, if you can head butt icebergs while you swim. How to Use Oracle VM Templates How to prepare an Oracle VM environment to use Oracle VM Templates, how to obtain a template, and how to deploy the template to your Oracle VM environment. Also how to create a virtual machine based on that template and how you can clone the template and change the clone's configuration. How to Use Oracle VM VirtualBox Templates How to use Oracle VM VirtualBox Templates in Oracle VM VirtualBox. Similar to the article above, but it describes how to download, install, and configure the templates within Oracle VM VirtualBox, instead of on bare metal. Other OTN Technical Articles by Yuli Vasiliev Retrieving, Transforming, and Consolidating Web Data with Oracle Database Setting Up, Configuring, and Using a WebLogic Server Cluster Cube Development for Beginners How to XQuery Non-JDBC Sources from JDBC Advanced Dimensional Design with Oracle Warehouse Builder Using the JDBC Connectivity Layer in Oracle Warehouse Builder High Performance Oracle JDBC Programming Python Data Persistence with Oracle Querying JPA Entities with JPQL and Native SQL - Rick Website Newsletter Facebook Twitter

    Read the article

  • ??????Java API?????????????????????????·??????????/????·???????|WebLogic Channel|??????

    - by ???02
    ??????Java???????????????????????????????????????1??????????Java??????????·???????????????????????????????????????????????????????Java????????????????????????????????·???????Oracle Coherence????????????????????????????????????????????????Coherence??Java?????????????????????????????????????????????????????2??????Oracle Coherence?Java???????????????????????????????????(???)?????????????Web??????????????Oracle Coherence ?????????????HashMap????????????????????Java?????????????????????????????????1???????????????????????????/??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ???JSP????????Struts???????Web???????????HttpSession?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ???Web???????????????Java?????????????????????????????????????????????????????????????????????????? ???????????????·??·?????????????????????????????????????Oracle Coherence????? Oracle Coherence???????????????????????????????????????????????????????????????????????????Oracle Coherence?????????????????????????????????????Web??????????????????????????????????????????????????Oracle Coherence????????????????????????????????????????????????????? ????Oracle Coherence??????????????????????????2???????? ???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ???????????????CPU??????????????????????????????????????????????????????????????????????????CPU??????????????????????????????????????????????????????Oracle Coherence??????????????????????????? ???????????????????????????????????????????????????????????????Oracle Coherence??????????????????????????????????/??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????1?1????????????????????????????????????????????????????Oracle Coherence???????????????3????? ???????Oracle Coherence???????????????????Java????????????????????????????????Oracle Coherence?????????????????????????3??????(1)??????????????? 1????Oracle WebLogic Server???????????·??????????????????????HTTP?????????????Oracle Coherence?????????? Oracle Coherence???Coherence*Web????????????????????????????????????????HttpSession?setAttribute?getAttribute??????????????????????Oracle Coherence?API???????????????????????Oracle Coherence?????????????Coherence???????????????????????????????????Oracle Coherence????????????????????/????????????????????·??????????????? ???????????????????????????RDB????????????????????????????????????????????????????????????RDB??????????????/?????????????????????????????????????????Oracle Coherence????????????????????????????????????????????????????????????????????????????????ANA SKY WEB???Oracle Coherence?????????????????????????????????????????????????????????????????????????????????????????????????ANA SKY WEB???????????????Oracle Coherence???????????????????10???????? ???????????·?????????????????????????????????????????????????????????????????????·???????????????Oracle Coherence??????????·???????????????????????????????????·???????????????????????????????????????????????(?????????????????????????)??????????????????(2)??????????????? 2????????Oracle Coherence??????????????????????????????? Oracle Coherence???Java Persistence API(JPA)???????·??????????????EclipseLink?Coherence?????????????????TopLink Grid??????????TopLink Grid??JPA????????????????????Oracle Coherence???????????????????JPQL(Java Persistence Query Language)?????????????Oracle Coherence????????????????????????????TopLink Grid???????JPA?????????????????????????????? ?????????????????????????????·?????1?????????????????????????????????????????????????????JPA????????????????????????·????????????????????????????Oracle Coherence???????????????????????????????????????????????????????? ???JPA?????????·???????????Grid Cache???Grid Read???Grid Entry??3?????????????Grid Cache??Oracle Coherence?2?????????????????Grid Read???????????(?????)?Oracle Coherence????????????????????????????(?????????????Coherence?????????)????Grid Entry???????/?????????Oracle Coherence??????(?????????????????????Coherence?????????????)??????????????????????????????????????????????????????(3)??/??????????????? 3??????????/?????????????Oracle Coherence???Java?Map API?????????????????????????????????????ID??????Map API????????????????????????????Oracle Coherence???????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????Oracle Coherence?????????ID??????Map API???????????????????????????????? ?????????????????????????????????????????????80??????????????????????·??????????????????????·????????????????????·???????????????????????????????????????Oracle Coherence???????????????????????Oracle Coherence???????????/??????????????·?????????????·????????????????????????????????????????????????????????????? ??????Java???API???????????Oracle Coherence?????????????????????????????3??????????????????????Java???????????????????????????????????????Oracle Coherence????API?????????????????????????????????3????????????

    Read the article

  • JPA and aggregate functions. How do I use the result of the query?

    - by Bogdan
    Hey guys, I'm new to ORM stuff and I need some help understanding something. Let's assume I have the following standard SQL query: SELECT *, COUNT(test.testId) AS noTests FROM inspection LEFT JOIN test ON inspection.inspId = test.inspId GROUP BY inspection.inspId which I want to use in JPA. I have an Inspection entity with a one-to-many relationship to a Test entity. (an inspection has many tests) I tried writing this in JPQL: Query query = em.createQuery("SELECT insp, COUNT(???what???) FROM Inspection insp LEFT JOIN insp.testList " + "GROUP BY insp.inspId"); 1) How do I write the COUNT clause? I'd have to apply count to elements from the test table but testList is a collection, so I can't do smth like COUNT(insp.testList.testId) 2) Assuming 1 is resolved, what type of object will be returned. It will definitely not be an Inspection object... How do I use the result?

    Read the article

  • Applying DDD principles in a RESTish web service

    - by Andy
    I am developing an RESTish web service. I think I got the idea of the difference between aggregation and composition. Aggregation does not enforce lifecycle/scope on the objects it references. Composition does enforce lifecycle/scope on the objects it contain/own. If I delete a composite object then all the objects it contain/own are deleted as well, while the deleting an aggregate root does not delete referenced objects. 1) If it is true that deleting aggregate roots does not necessary delete referenced objects, what sense does it make to not have a repository for the references objects? Or are aggregate roots as a term referring to what is known as composite object? 2) When you create an web service you will have multiple endpoints, in my case I have one entity Book and another named Comment. It does not make sense to leave the comments in my application if the book is deleted. Therefore, book is a composite object. I guess I should not have a repository for comments since that would break the enforcement of lifecycle and rules that the book class may have. However I have URL such as (examples only): GET /books/1/comments POST /books/1/comments Now, if I do not have a repository for comments, does that mean I have to load the book object and then return the referenced comments? Am I allowed to return a list of Comment entities from the BookRepository, does that make sense? The repository for Book may eventually become rather big with all sorts of methods. Am I allowed to write JPQL (JPA queries) that targets comments and not books inside the repository? What about pagination and filtering of comments. When adding a new comment triggered by the POST endpoint, do you need to load the book, add the comment to the book, and then update the whole book object? What I am currently doing is having a own CommentRepository, even though the comments are deleted with the book. I could need some direction on how to do it correct. Since you are exposing not only root objects in RESTish services I wonder how to handle this at the backend. I am using Hibernate and Spring.

    Read the article

  • JPA 2 and Hibernate 3.5.1 MEMBER OF query doesnt work.

    - by Ed_Zero
    I'm trying the following JPQL and it fails misserably: Query query = em.createQuery("SELECT u FROM User u WHERE 'admin' MEMBER OF u.roles"); List users = query.query.getResultList(); I get the following exception: ERROR [main] PARSER.error(454) | <AST>:0:0: unexpected end of subtree java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: unexpected end of subtree [SELECT u FROM com.online.data.User u WHERE 'admin' MEMBER OF u.roles] ERROR [main] PARSER.error(454) | <AST>:0:0: expecting "from", found '<ASTNULL>' ... ... Caused by: org.hibernate.hql.ast.QuerySyntaxException: unexpected end of subtree [SELECT u FROM com.online.data.User u WHERE 'admin' MEMBER OF u.roles] I have Spring 3.0.1.RELEASE, Hibernate 3.5.1-Final and maven to glue dependencies. User class: @Entity public class User { @Id @Column(name = "USER_ID") @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(unique = true, nullable = false) private String username; private boolean enabled; @ElementCollection private Set<String> roles = new HashSet<String>(); ... } Spring configuration: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/tx/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- Reading annotation driven configuration --> <tx:annotation-driven transaction-manager="transactionManager" /> <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="100" /> <property name="maxWait" value="1000" /> <property name="poolPreparedStatements" value="true" /> <property name="defaultAutoCommit" value="true" /> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> <property name="dataSource" ref="dataSource" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showSql" value="true" /> <property name="databasePlatform" value="${hibernate.dialect}" /> </bean> </property> <property name="loadTimeWeaver"> <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" /> </property> <property name="jpaProperties"> <props> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.current_session_context_class">thread</prop> <prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">false</prop> <prop key="hibernate.show_comments">true</prop> </props> </property> <property name="persistenceUnitName" value="punit" /> </bean> <bean id="JpaTemplate" class="org.springframework.orm.jpa.JpaTemplate"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> </beans> Persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence 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"> <persistence-unit name="punit" transaction-type="RESOURCE_LOCAL" /> </persistence> pom.xml maven dependencies. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> <version>${hibernate.version}</version> <type>pom</type> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> <type>jar</type> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-taglibs</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-acl</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.annotation</groupId> <artifactId>jsr250-api</artifactId> <version>1.0</version> </dependency> <properties> <!-- Application settings --> <spring.version>3.0.1.RELEASE</spring.version> <hibernate.version>3.5.1-Final</hibernate.version> Im running a unit test to check the configuration and I am able to run other JPQL queries the only ones that I am unable to run are the IS EMPTY, MEMBER OF conditions. The complete unit test is as follows: TestIntegration @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/spring/dataLayer.xml"}) @Transactional @TransactionConfiguration public class TestUserDaoImplIntegration { @PersistenceContext private EntityManager em; @Test public void shouldTest() throws Exception { try { //WORKS Query query = em.createQuery("SELECT u FROM User u WHERE 'admin' in elements(u.roles)"); List users = query.query.getResultList(); //DOES NOT WORK } catch (Exception e) { e.printStackTrace(); throw e; } try { Query query = em.createQuery("SELECT u FROM User u WHERE 'admin' MEMBER OF u.roles"); List users = query.query.getResultList(); } catch (Exception e) { e.printStackTrace(); throw e; } } }

    Read the article

  • Under what circumstances will an entity be able to lazily load its relationships in JPA

    - by Mowgli
    Assuming a Java EE container is being used with JPA persistence and JTA transaction management where EJB and WAR packages are inside a EAR package. Say an entity with lazy-load relationships has just been returned from a JPQL search, such as the getBoats method below: @Stateless public class BoatFacade implements BoatFacadeRemote, BoatFacadeLocal { @PersistenceContext(unitName = "boats") private EntityManager em; @Override public List<Boat> getBoats(Collection<Integer> boatIDs) { if(boatIDs.isEmpty()) { return Collections.<Boat>emptyList(); } Query query = em.createNamedQuery("getAllBoats"); query.setParameter("boatID", boatIDs); List<Boat> boats = query.getResultList(); return boats; } } The entity: @Entity @NamedQuery( name="getAllBoats", query="Select b from Boat b where b.id in : boatID") public class Boat { @Id private long id; @OneToOne(fetch=FetchType.LAZY) private Gun mainGun; public Gun getMainGun() { return mainGun; } } Where will its lazy-load relationships be loadable (assuming the same stateless request): Same JAR: A method in the same EJB A method in another EJB A method in a POJO in the same EJB JAR Same EAR, but outside EJB JAR: A method in a web tier managed bean. A method in a web tier POJO. Different EAR: A method in a different EAR which receives the entity through RMI. What is it that restricts the scope, for example: the JPA transaction, persistence context or JTA transaction?

    Read the article

  • Java EE 6 and NoSQL/MongoDB on GlassFish using JPA and EclipseLink 2.4 (TOTD #175)

    - by arungupta
    TOTD #166 explained how to use MongoDB in your Java EE 6 applications. The code in that tip used the APIs exposed by the MongoDB Java driver and so requires you to learn a new API. However if you are building Java EE 6 applications then you are already familiar with Java Persistence API (JPA). Eclipse Link 2.4, scheduled to release as part of Eclipse Juno, provides support for NoSQL databases by mapping a JPA entity to a document. Their wiki provides complete explanation of how the mapping is done. This Tip Of The Day (TOTD) will show how you can leverage that support in your Java EE 6 applications deployed on GlassFish 3.1.2. Before we dig into the code, here are the key concepts ... A POJO is mapped to a NoSQL data source using @NoSQL or <no-sql> element in "persistence.xml". A subset of JPQL and Criteria query are supported, based upon the underlying data store Connection properties are defined in "persistence.xml" Now, lets lets take a look at the code ... Download the latest EclipseLink 2.4 Nightly Bundle. There is a Installer, Source, and Bundle - make sure to download the Bundle link (20120410) and unzip. Download GlassFish 3.1.2 zip and unzip. Install the Eclipse Link 2.4 JARs in GlassFish Remove the following JARs from "glassfish/modules": org.eclipse.persistence.antlr.jar org.eclipse.persistence.asm.jar org.eclipse.persistence.core.jar org.eclipse.persistence.jpa.jar org.eclipse.persistence.jpa.modelgen.jar org.eclipse.persistence.moxy.jar org.eclipse.persistence.oracle.jar Add the following JARs from Eclipse Link 2.4 nightly build to "glassfish/modules": org.eclipse.persistence.antlr_3.2.0.v201107111232.jar org.eclipse.persistence.asm_3.3.1.v201107111215.jar org.eclipse.persistence.core.jpql_2.4.0.v20120407-r11132.jar org.eclipse.persistence.core_2.4.0.v20120407-r11132.jar org.eclipse.persistence.jpa.jpql_2.0.0.v20120407-r11132.jar org.eclipse.persistence.jpa.modelgen_2.4.0.v20120407-r11132.jar org.eclipse.persistence.jpa_2.4.0.v20120407-r11132.jar org.eclipse.persistence.moxy_2.4.0.v20120407-r11132.jar org.eclipse.persistence.nosql_2.4.0.v20120407-r11132.jar org.eclipse.persistence.oracle_2.4.0.v20120407-r11132.jar Start MongoDB Download latest MongoDB from here (2.0.4 as of this writing). Create the default data directory for MongoDB as: sudo mkdir -p /data/db/sudo chown `id -u` /data/db Refer to Quickstart for more details. Start MongoDB as: arungup-mac:mongodb-osx-x86_64-2.0.4 <arungup> ->./bin/mongod./bin/mongod --help for help and startup optionsMon Apr  9 12:56:02 [initandlisten] MongoDB starting : pid=3124 port=27017 dbpath=/data/db/ 64-bit host=arungup-mac.localMon Apr  9 12:56:02 [initandlisten] db version v2.0.4, pdfile version 4.5Mon Apr  9 12:56:02 [initandlisten] git version: 329f3c47fe8136c03392c8f0e548506cb21f8ebfMon Apr  9 12:56:02 [initandlisten] build info: Darwin erh2.10gen.cc 9.8.0 Darwin Kernel Version 9.8.0: Wed Jul 15 16:55:01 PDT 2009; root:xnu-1228.15.4~1/RELEASE_I386 i386 BOOST_LIB_VERSION=1_40Mon Apr  9 12:56:02 [initandlisten] options: {}Mon Apr  9 12:56:02 [initandlisten] journal dir=/data/db/journalMon Apr  9 12:56:02 [initandlisten] recover : no journal files present, no recovery neededMon Apr  9 12:56:02 [websvr] admin web console waiting for connections on port 28017Mon Apr  9 12:56:02 [initandlisten] waiting for connections on port 27017 Check out the JPA/NoSQL sample from SVN repository. The complete source code built in this TOTD can be downloaded here. Create Java EE 6 web app Create a Java EE 6 Maven web app as: mvn archetype:generate -DarchetypeGroupId=org.codehaus.mojo.archetypes -DarchetypeArtifactId=webapp-javaee6 -DgroupId=model -DartifactId=javaee-nosql -DarchetypeVersion=1.5 -DinteractiveMode=false Copy the model files from the checked out workspace to the generated project as: cd javaee-nosqlcp -r ~/code/workspaces/org.eclipse.persistence.example.jpa.nosql.mongo/src/model src/main/java Copy "persistence.xml" mkdir src/main/resources cp -r ~/code/workspaces/org.eclipse.persistence.example.jpa.nosql.mongo/src/META-INF ./src/main/resources Add the following dependencies: <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.jpa</artifactId> <version>2.4.0-SNAPSHOT</version> <scope>provided</scope></dependency><dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.nosql</artifactId> <version>2.4.0-SNAPSHOT</version></dependency><dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.7.3</version></dependency> The first one is for the EclipseLink latest APIs, the second one is for EclipseLink/NoSQL support, and the last one is the MongoDB Java driver. And the following repository: <repositories> <repository> <id>EclipseLink Repo</id> <url>http://www.eclipse.org/downloads/download.php?r=1&amp;nf=1&amp;file=/rt/eclipselink/maven.repo</url> <snapshots> <enabled>true</enabled> </snapshots> </repository>  </repositories> Copy the "Test.java" to the generated project: mkdir src/main/java/examplecp -r ~/code/workspaces/org.eclipse.persistence.example.jpa.nosql.mongo/src/example/Test.java ./src/main/java/example/ This file contains the source code to CRUD the JPA entity to MongoDB. This sample is explained in detail on EclipseLink wiki. Create a new Servlet in "example" directory as: package example;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * @author Arun Gupta */@WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})public class TestServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet TestServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>"); try { Test.main(null); } catch (Exception ex) { ex.printStackTrace(); } out.println("</body>"); out.println("</html>"); } finally { out.close(); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }} Build the project and deploy it as: mvn clean packageglassfish3/bin/asadmin deploy --force=true target/javaee-nosql-1.0-SNAPSHOT.war Accessing http://localhost:8080/javaee-nosql/TestServlet shows the following messages in the server.log: connecting(EISLogin( platform=> MongoPlatform user name=> "" MongoConnectionSpec())) . . .Connected: User: Database: 2.7  Version: 2.7 . . .Executing MappedInteraction() spec => null properties => {mongo.collection=CUSTOMER, mongo.operation=INSERT} input => [DatabaseRecord( CUSTOMER._id => 4F848E2BDA0670307E2A8FA4 CUSTOMER.NAME => AMCE)]. . .Data access result: [{TOTALCOST=757.0, ORDERLINES=[{DESCRIPTION=table, LINENUMBER=1, COST=300.0}, {DESCRIPTION=balls, LINENUMBER=2, COST=5.0}, {DESCRIPTION=rackets, LINENUMBER=3, COST=15.0}, {DESCRIPTION=net, LINENUMBER=4, COST=2.0}, {DESCRIPTION=shipping, LINENUMBER=5, COST=80.0}, {DESCRIPTION=handling, LINENUMBER=6, COST=55.0},{DESCRIPTION=tax, LINENUMBER=7, COST=300.0}], SHIPPINGADDRESS=[{POSTALCODE=L5J1H7, PROVINCE=ON, COUNTRY=Canada, CITY=Ottawa,STREET=17 Jane St.}], VERSION=2, _id=4F848E2BDA0670307E2A8FA8,DESCRIPTION=Pingpong table, CUSTOMER__id=4F848E2BDA0670307E2A8FA7, BILLINGADDRESS=[{POSTALCODE=L5J1H8, PROVINCE=ON, COUNTRY=Canada, CITY=Ottawa, STREET=7 Bank St.}]}] You'll not see any output in the browser, just the output in the console. But the code can be easily modified to do so. Once again, the complete Maven project can be downloaded here. Do you want to try accessing relational and non-relational (aka NoSQL) databases in the same PU ?

    Read the article

< Previous Page | 1 2