w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Error in Hibernate NamedQuery
It seems you cannot execute a left join unless you map an association between the entities. In my case, OrganizationExt is not mapped into Header, even though the location is present. So it seems like I might create an Oracle view containing this information and create a Hibernate mapping directly into that.

Categories : Java

Java Hibernate NamedQuery resultTransformer
question #1: Most probably you need to add alias to name field in select list select s.name as name from com.company.generic.model.Student s where s.id=:id so Hibernate can find the setName(String) method in Student.class. Using criteria the equivalent is session.createCriteria(Student.class) .add(Restrictions.eq("id",id)) .setProjection(Projections.property("name").as("name")) .setResultTransformer(Transformers.aliasToBean(Student.class)); question #2: Named query select list is the projection. question #3: see answers above

Categories : Java

AppFuse - Spring Hibernate - no session found for the current thread
This may have been asked more than a year ago but I hope I could help someone. I have had similar issue when starting out with appfuse framework. It turns out that I keep forgetting to add single argument constructor in my custom manager implementation. I think, most important part is in passing the autowired dao instance up to parent classes. Expected custom manager implementation example: @Service("customManager") public class CustomManagerImpl extends GenericManagerImpl<User, Long> implements CustomManager {     private UserDao userDao;          @Autowired     public CustomManagerImpl(UserDao userDao){     &

Categories : Spring

Spring + Hibernate: No Hibernate Session bound to thread
If you have defined a TransactionManager in your spring context you have to specify @Transactional somewhere in the stack. Otherwise you will get the exception you encountered because you are trying to run a query outside of a transaction. There are workarounds to this such specifying current_session_context_class in your hibernate configuration to thread or <property name="current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property> but it's not production safe.. The possible values for current_session_context_class are jta, thread and managed. Further to that, jta and thread are supported by hibernate out of box. thread context is used in most stand alone hibernate apps or those based on light weight frameworks like Spring and jta is used in

Categories : Java

spring mvc 3 with hibernate (and hibernate.hbm2ddl.auto)
You seem to be missing the spring-tx jar from your classpath given this line 15:49:04,031 ERROR [org.springframework.beans.factory.support.DefaultListableBeanFactory] (MSC service thread 1-3) Destroy method on bean with name '(inner bean)' threw an exception: java.lang.NoClassDefFoundError: org/springframework/transaction/support/TransactionSynchronization You can get it here. You actually seem to be missing much more than that. java.lang.ClassNotFoundException: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean Get all the spring jars from the here.

Categories : Java

Spring, JPA, Hibernate, Tomcat: Unable to find persistence unit when loading Spring application context
As far I understood from my recent expirience of setting up 2 EntityManagerFactory in the same application - @PersistenceUnit(unitName="myPU") just doesn't work at all. I would suggest to inject EntityManager, not EntityManagerFactory. This is clear since you always know which EMF is used. Same for specifying right TransactionManager. Updated code of the service class: @Service public class CompetenceAreaManager { @PersistenceContext(unitName = "emf1") private EntityManager em; @SuppressWarnings("unchecked") @Transactional(transactionManager="transactionManager1", readOnly=true) public List<CompetenceArea> getCompetenceAreas() { List<CompetenceArea> competenceAreaList = null; Query q = em.createNamedQuery(CompetenceArea.FIND_ALL);

Categories : Java

Spring MVC bind hibernate session factory other thread in spring web mvc
You need to either go through AOP decorated transactional bean (e.g. your service layer annotated with @Transactional), or you need to use TransactionTemplate: new TransactionTemplate(txManager).execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { // Your Hibenrate stuff return null; } });

Categories : Spring

Spring Bean not found for Spring Security RememberMe?
Cannot convert value of type [groovy.util.ConfigObject] to required type [int] for property 'tokenLength' This suggests to me that you don't have a grails.plugins.springsecurity.rememberMe.persistentToken.tokenLength property set in your grailsApplication.config - when you ask a ConfigObject for a non-existent key what it returns to you is a new empty ConfigObject.

Categories : Java

What is the correct procedure for including a Maven-Spring-Roo-Hibernate jar in a Non-Maven-Non-Spring project?
Because the application context don't aware about the model. You are creating the model out of the appcontext. if you get the Model using getBean("MyUser"); some thing like that will work. else auto-wire the model and use that model for your crud operations. You can see the following code in MyUser - @PersistenceContext rotected transient EntityManager entityManager; Then only the entityManager object will initialized inside the the Myuser. @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath*:/META-INF/spring/applicationContext.xml"}) public class SomeTest extends AbstractJUnit4SpringContextTests { @Autowired MyUser myUser; // use this object for ur crud operations @Test public void someTest() throws Exce

Categories : Java

JPA-Hibernate-EJB: More than one row with the given identifier was found
In your database you have a table which have an inverse relationship data added. for example your tables relaiontionship is many to one but your tables data is like many to many.you must delete like this rows.

Categories : Hibernate

hibernate.properties not found
Hibernate by default at startup looks for hibernate.properties and hibernate.cfg.xml and logs a debug message if those aren't found. So disable debug/info for hibernate and you will not see the message.see http://forum.springsource.org/showthread.php?127317-hibernate-properties-with-JavaConfig also see hibernate properties not found

Categories : Java

JPA @namedQuery with "IN" expression
Pass a List to the setParameter method instead of a String. The generic type argument of List should correspond with the type of your departmentIds field. List<Integer> ids = new ArrayList<Integer>(); //this should be your id column's type ids.add(1); ids.add(2); ids.add(3); query.setParameter("departmentsIds",ids);

Categories : Java

JPA createQuery or @NamedQuery
Basically @NamedQuery is just like typedQuery, typedQuery is the result of create query: TypedQuery<USER> hql = entityManager.createQuery(query); The only difference between @NamedQuery and typedQuery is named query is on the difference place than the code, and checked when the session factory is created. Performance issue difference is just about building strings, so unless your join is in a hundred or thousands of table you really won't find any difference about those two.

Categories : Hibernate

Hibernate + Derby. Database not found
You can try using create = true with url string. <property name=”hibernate.connection.url”>jdbc:derby:DBUSER;create=true</property> It creates the standard database specified within the database connection URL Derby system and then connects to it. If the database cannot be created, the error appears in the error log and the connection attempt fails with an SQLException indicating that the database cannot be found. If the database already exists, creates a connection to the existing database and an SQLWarning is issued.

Categories : Java

Hibernate: Mapping not found exception
Move User.hbm.xml to proper package (testing.ground.beans) in src/main/resources . I guess your build tool doesn't pick the resources from src/main/java

Categories : Java

Why should we use spring's hibernate?
Thanks to @Wand Maker. I have found the answer I need in the link provided: static.springsource.org/spring/docs/3.0.x/reference/orm.html at the 13.3 Hibernate portion which explains the different ways to implement DAO using spring hibernate.

Categories : Spring

Difference between @NamedQuery and @NamedNativeQuery in JPA-EclipseLink
A native query isn't JPQL. A regular query is converted by the persistence provider into something the underlying persistence system understands (such as SQL SELECT, or a NoSQL retrieval). A native query, while not portable, is written directly in the native language of the store so that you can use special features (like PostgreSQL's IP address manipulation) at the cost of portability.

Categories : Java

JPA Eclipselink NamedQuery vs Query COUNT
Short answer: em.createQuery is used for creation of dynamic queries. Return type is determined by the return type of the QL language ("SELECT COUNT(c.id)" in the example above). em.createNamedQuery is used for creation of static queries. Return type can be type casted, for example: Object q = em.createNamedQuery(Comm.COUNTLIKEVALUEINHOLDER) .setParameter("search1", "bla%") .setParameter("search2", "bla2") .setParameter("type", t) .setParameter("holder", h) .getSingleResult(); Integer count = (Integer) q; ` see also:http://www.objectdb.com/java/jpa/query/api

Categories : Java

How to display date and string when using @NamedQuery
If your receiving test.entity.Employee@750d24b2 your not accessing a String on the JSF, instead your accessing a class via JSF EL. You should access a field on the Employee class like: <h:outputText value="#{req.employee.empNumber}" /> This assumes that the req attribute contains get/set methods for employee and employee contains get/set methods for empNumber. With these accessors in place JSF EL should display the value of the empNumber. For displaying the date, I would recommend using JSF tags. <h:outputText value="#{req.someDate}" > <f:convertDateTime pattern="dd.MM.yyyy HH:mm" /> </h:outputText> Documentation

Categories : Java

Enum class not found when using EnumType in Hibernate hbm file
I ended using the solution that I proposed by adding an ant task that only compiles the classes needed to run hbm2java. The task is named "build-hibernate-dependencies", so I simply add a depends attribute to my hbm2java target for it: <target name="hbm2java" depends="build-hibernate-dependencies"> <hibernatetool destdir="${src.dir}"> ... </hibernatetool> </target> The target "build-hibernate-dependencies" compiles the enums to the build directory: <target name="build-hibernate-dependencies"> <mkdir dir="${build.dir}" /> <javac destdir="${build.dir}"> <src path="${src.dir}/enums" /> </javac> </target> And after that, I can now compile the entire project.

Categories : Hibernate

hibernate+spring get max id in range
What about something like this? List<Student> results = sessionFactory.getCurrentSession() .createCriteria(Student.class) .setProjection(Projections.max("id")) .add(Restrictions.between("id", 30000, 40000)).list(); if (results != null && results.size() > 0) { s = results.get(0); } else { // not found }

Categories : SQL

Ajax with spring mvc + hibernate
Thats too broad question to answer in depth. Seems you miss some knowledge how spring mvc works itself. You need to fetch List of rows using hibernate, then add it to mvc model in your controller then you will be able to list them using jsp. If you have it, then start reading about contollers which read/write JSON ( @RequestBody/@ResponseBody ).

Categories : Ajax

Spring Autowired DAO with hibernate.cfg.xml
You just define your bean twice! One with XML configuration: <bean id="accountingAccountDAO" class="com.tom.project.dao.accounting.HibernateAccountingAccountDAO"> <property name="sessionFactory" ref="sessionFactory" /> </bean> and one with @Repository annotation @Repository("accountingAccountDAO") public class HibernateAccountingAccountDAO implements AccountingAccountDAO Remove XML definition to get it worked!

Categories : Spring

Spring Framework - Hibernate
I'm not expertise in spring but I assume that you have a problem with your service, if you use an interface you should inject ut and not your class... see this track... Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

Categories : Java

Struts spring Hibernate
It is missing a jar file. ServletContextListener is in servlet-api.jar include that jar file in your project. (ServletRequestListener is in the same jar file)

Categories : Hibernate

Hibernate Envers vs Spring AOP
I have just started using Hibernate Envers for auditing and so far I am very much satisfied with it. Pros: 1. We literally don't have to write a single line of code. 2.It also captures the userName and timestamp automatically through RevisionEvent, a very simple thing to configure. 3.the code follows JPA annotations, not hibernate. 4.Well if someone is using hibernate then why not use its entire feature. 5.This feature(Envers) is developed specifically to capture auditing. People are continuously working on upgrade and making it more user friendly. 6.One can write his own event listeners like for update,delete,insert etc: Cons: 1.Creates lots of AUD_ tables. However we can configure the table which we want to AUDIT. 2.It will never capture HQL queries automatically.

Categories : Misc

Hibernate @Valid and Spring MVC
The path to your messages file is wrong, the content of the resources directory is directly added to the classpath (just like the java directory). More information can be found on the maven website So instead of classpath:/resources/i18n/messages use classpath:/i18n/messages and the same goed for the errors file ofcourse.

Categories : Java

in memory db hibernate spring
Following this answer, and knowing your XML mapping, I'd suggest the following annotation changes to orderId: @Id @GeneratedValue @Column(name="orderId", columnDefintion="BIGINT") String orderId; That's assuming that @GeneratedValue equates to a "native" generator as in your XML. You might need to use an @GenericGenerator instead with a strategy=native instead more like this: @Id @GeneratedValue(generator="my-native-generator") @GenericGenerator(name="my-native-generator", strategy = "native") @Column(name="orderId", columnDefintion="BIGINT") String orderId;

Categories : Spring

Hibernate Spring Joins
The tables will be joined if their relationship is one-to-many. In your domain files, the relationship between Employee_Domain and Employee is one-to-one. Try to change it to: @OneToMany(mappedBy="Employee_Domain") private List<Employee> employees= new ArrayList<Employee>(); And the join will happen.

Categories : Hibernate

JPA: NamedQuery parameter in query string for switches
NamedQuery is static query. You can't put dynamic query value (i.e ASC or DESC) in NamedQuery. You should use DynamicQuery(i.e. JPQL) or Native Query or Criteria to get your desired output.

Categories : Java

Spring MVC and hibernate combining models
The easiest way IMHO, is to create a database view with all you the stuff you need and create a Hibernate entity mapping this view. Use insertable = false, updatable = false to map your columns to avoid that anybody tries to update the view using this new Entity. This way you have to deal with data using SQL instead Hibernate, so I think is easier and can help you to solve the issue.

Categories : Spring

implementing i18n spring mvc with hibernate
i18n and data persistence (ie hibernate ORM) is a different concept. Since you mentioned Spring, I would suggest start with Spring's i18n support. A good way to start is to create a Spring Roo project on STS. File -> New -> Spring Roo Project -> (enter project name, top level pkg) -> select packaging WAR On the Roo Shell, setup mvc by using web mvc setup Run the resulting project using maven embedded tomcat container mvn clean tomcat:run You will get a Spring MVC project complete with i18n and language switcher. Just a little taste on how you can localize your app: # File: messages.properties ----------- ... hello_prefix=Hello {0} ... # File: messages_zh_CN.properties ----- ... hello_prefix=你好 {0} ... Switch locale to Chinese simplified using `http://mycoolwebsite.com?lang=zh

Categories : Spring

Spring + Hibernate Not able to address issue
The application is missing the hibernate-core-x.x.x.jar file. You will need to find the appropriate version of the jar. Use FindJar: http://www.findjar.com/jar/org/hibernate/hibernate-core/3.3.2.GA/hibernate-core-3.3.2.GA.jar.html The class java.lang.ClassNotFoundException: org.hibernate.cache.CacheProvider is included in version of Hibernate before version 4.0. I would update all of your libraries to use the 4.0 version.

Categories : Spring

Connect to multiple DB from Hibernate and Spring
At the end I've solve it like that: @Repository public class TstDao{ private static Logger LOG = LoggerFactory.getLogger(TstDao.class); @Autowired @Qualifier(value="transactionManager2") private PlatformTransactionManager tm; private TransactionTemplate transactionTemplate; @PostConstruct public void init(){ transactionTemplate = new TransactionTemplate(tm); LOG.debug("tm="+tm); } @Autowired @Qualifier(value="sessionFactory2") SessionFactory sessionFactory; public List<Obj_Test> getAllUsers(){ return transactionTemplate.execute(new TransactionCallback<List<Obj_Test>>() { @Override public List<Obj_Test> doInTransaction(TransactionStatus status) { Cr

Categories : Java

Spring framework hibernate beans
It looks like you have multiple versions of hibernate on your classpath. The root cause of this error is Caused by: java.lang.VerifyError: class org.hibernate.type.WrappedMaterializedBlobType overrides final method getReturnedClass.()Ljava/lang/Class; My guess is the API changed slightly between versions and your app is loading the wrong version of hibernate (possibly through a transient dependency). It's possible it works on your friend's configuration because the classes just happen to be loaded in the correct order. Verify that are not including multiple versions, and if you are, try to remove the duplicate (or at least force the right version in the dependencyManagement section of your pom).

Categories : Spring

Several Read-Only DB Connections in Spring and Hibernate
You should be able to do that with AbstractRoutingDataSource class in Spring. This blog should help you. You can wire each data source for each of your controllers.

Categories : Spring

Junit with HSQL/H2 without Spring/Hibernate
I ususally do something like this: In the @Before method I establish a connection to a memory database, something like this: @Before public void setup() { this.dbConnection = DriverManager.getConnection("jdbc:hsqldb:mem:testcase;shutdown=true", "sa", null); } The connection is stored in an instance variable, so it's available for each test. Then if all tests share the same tables, I also create those inside the setup() method, otherwise each tests creates its own tables: @Test public void foo() { Statement stmt = this.dbConnection.createStatement(); stmt.execute("create table foo (id integer)"); this.dbConnection.commit(); ... now run the test } In the @After method I simplic close the connection which means the in-memory database gets wiped and the next test runs w

Categories : Java

Spring-Hibernate Caching with Memcached
Below mentioned are the steps you can follow. pom.xml changes to include the abstract cache mechanism for memcache and client implementation using xmemcache. com.google.code.simple-spring-memcached spring-cache 3.1.0 <dependency> <groupId>com.google.code.simple-spring-memcached</groupId> <artifactId>xmemcached-provider</artifactId> <version>3.1.0</version> </dependency> Note : You need to include cglib too as this is aop based. configuration.xml file changes **defining beans** <bean name="cacheManager" class="com.google.code.ssm.spring.SSMCacheManager"> <property name="caches"> <set> <bean class="com.google.code.ssm.spring.SSMCache">

Categories : Spring

Spring, Hibernate and Lazy initialize
Your configuration lacks a filter-mapping for the OpenSessionInViewFilter, without that it is going to do exactly nothing. Next to that your filter is commented out. add <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <servlet-name>appServlet</servlet-name> </filter-mapping> and activate your filter.

Categories : Spring

Spring mvc and Hibernate validator, error
Change your method signature to put the BindingResult parameter next to the at @Valid parameter public String guardaSimCard(@ModelAttribute("validator") @Valid CatalogoSimCardValidator validator, BindingResult result, HttpServletRequest request, Model model) { I assume the Exception you get is an IllegalStateException (it would help if you posted it) coming from an ErrorsMethodArgumentResolver and states An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the @RequestBody or the @RequestPart arguments to which they apply: [...]

Categories : Java



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.