We are using hibernate template by using the following package.
org.springframework.orm.hibernate3.HibernateTemplate;
protected HibernateTemplate template = null;
here template is from org.springframework.orm.hibernate3.HibernateTemplate package. I am not able to understand how to interpret this package.
is it the spring hibernate because package name starts with springframework. But there is no such spring hibernate. There is only ORM module i guess in spring.
Can anyone help me understand how to understand this package org.springframework.orm.hibernate3.HibernateTemplate.
update:
below is the exactly repository class I am using
#Repository
#Transactional
public class ABCDImplements ABCD {
private Log logger = LogFactory.getLog(this.getClass());
protected HibernateTemplate template = null;
#Resource(name = "abcSessionFactory")
protected SessionFactory sessionFactory;
#Autowired
public void init(SessionFactory sessionFactory) {
setSessionFactory(sessionFactory);
}
public void setSessionFactory(SessionFactory sessionFactory) {
template = new HibernateTemplate(sessionFactory);
}
}
Spring provides integration with Hibernate 3 and 4 under the form of HibernateTemplate, and the one you show provides integration with Hibernate 3.
The main goal of this class was to provide a Hibernate session via a callback, and another important functionality was to translate Hibernate exceptions to Spring exceptions.
The use of this class is not recommended anymore, have a look at this answer. The recommended way is to use the #Transactional annotation.
Related
hi,everyone i am a newcomer for hibernate. i write code with struts+spring+hibernate ,i encounter a trouble in this code
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.integration.entity.User;
public class UserDAOImpl extends HibernateDaoSupport implements UserDAO {
#Override
public User getUser(String name) {
// TODO Auto-generated method stub
String hsql="from User u where u.name='"+name+"'";
User result=(User)((Query) this.getHibernateTemplate().find(hsql)).uniqueResult();
return result;
}
the question is Query and uniqueResult() is deprecated ,how will i modify my code? thanks
The problem is not only in your method. The hole class HibernateDaoSupportis deprecated as it said here
I recommend you to configure your SessionFactory via Spring (as I see you use it) and use createQuery method to pass there your hql. Here is the example:
Configuring session factory:
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
p:packagesToScan="-your-model-"
p:hibernateProperties-ref="-your-properties-"
p:dataSource-ref="-your-datasource-"/>
The DAO method:
private final SessionFactory sessionFactory;
// Injecting session factory via constructor
#Autowired
public UserDAO(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
String hql="from User u where u.name=:name";
public User getByUsername(String name) {
return sessionFactory.getCurrentSession()
.createQuery(hql, User.class)
.setParameter("name", name)
.uniqueResult();
}
Also your code us not secure. You should use params of query for preventing sql injections. I show it in my method. Read about session factory and injecting it in DAO.
Good luck.
EDIT
Also it's just an example. You can configure everything as you wish (via java code, not xml for example)
I am currently looking into integrating Mockito and JUnit into my Wicket/Spring/Hibernate project and have found a tutorial on how to do this using annotations.
Trouble is I am unfamiliar with #Autowired and after a look on google I am finding it hard to see the difference between this annotation and the #SpringBean annotation.
Are they one in the same or is there a difference I should be aware of ?
My code to offer some context to this question:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:applicationContext.xml"})
#TransactionConfiguration(transactionManager = "txManager", defaultRollback = false)
public class TestHome
{
private WicketTester tester;
#Autowired
private ApplicationContext ctx;
#Autowired
private WebApplication webApplication;
#Before
public void setUp() {
tester = new WicketTester(webApplication);
}
#Test
#Transactional
#Rollback(true)
public void testRenderHomePage() {
tester.startPage(Home.class);
tester.assertRenderedPage(Home.class);
tester.assertComponent("home", Home.class);
}
}
If you use Wicket SpringComponentInjector, it uses its own injection. The #Autowired annotation is a Springframework annotation, but Wicket SpringComponentInjector ignores that. So the Wicket annotation is #SpringBean that marks a field to be autowired (injected) by Spring bean or component that has to exist in Spring context.
In you code snippet you use the SpringJUnit4ClassRunner runner, so your fields are injected by Spring, so it is correct.
See an example, how to use SpringComponentInjector at How can I get a Spring bean injected in my custom Wicket model class?
I have decided to use Spring, Hibernate, and Restlet to create a web service. I am new to all of these three technologies. My question is this: How do I decide whether to use JPA's EntityManager or Hibernate's HibernateTemplate?
Code snippet for JPA's EntityManager:
protected EntityManager entityManager;
#PersistenceContext
public void setEngityManager(EntityManager entityManger) {
this.entityManager = entityManager;
}
Code snippet for Hibernate's HibernateTemplate:
private SessionFactory sessionFactory;
private HibernateTemplate hibernateTemplate;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
If you are someone who like interface-based-implementation, then JPA is the interface definition and Hibernate is one of the implementations. We decided to use JPA semantics in our project (with a very long term plan to replace Hibernate with something similar and light-weight probably).
If you want to stick to hibernate in future, then no point in using EntityManagerFactory, you can go ahead and use SessionFactory. And just inject definition for this using java based configuration or xml. It must be available in application context.
But in future if you might want to move to different jpa provider, like toplink etc, then you should use EntityManagerFactory as it allows you to have implementation from various provider. Because providers implement jpa specification. So in future you just need to have different configuration in your application context and you should be able to use that.
I am making a web application on STS. I am using jars of Spring 3.1.0 and HIbernate 4.0.1. I am including jars in project build path.
In DAO layer when I am trying to make a HibernateTemplate object , it is not getting instantiate, It is null there. I don't understand why it is null.
Earlier I was getting an error like NoClassDefinitionFound: org.springframework.orm.hibernate3.HibernateTemplate....Then I included these jars in WEB-INF->lib folder and then this error was removed but still hibernateTemplate object is null. Can there be any issue regarding position of beans.xml in project folders. ? Can anyone help me.
Below is code for my beans.xml and Userinfo.java.
[b]Beans.xml[/b]
Only relevant part of bean.xml
<bean id="hibTemplateBean" class="org.springframework.orm.hibernate3.HibernateTemplate" >
<property name="sessionFactory" ref="sfBean" />
</bean>
[b]UserinfoDao.java[/b]
package com.home.dao;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.home.pojo.User;
public class UserinfoDao {
public UserinfoDao() {
super();
}
private static HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
UserinfoDao.hibernateTemplate = hibernateTemplate;
}
public static void fetchUserInfo(){
try{
User user = (User)hibernateTemplate.get(User.class, 111);
}catch(NullPointerException npe){
npe.printStackTrace();
}
}
}
You are using Hibernate 4 and you are using org.springframework.orm.hibernate3.HibernateTemplate from Hibernate 3 package.
This template is not supported anymore. You can do declarative transaction management.
Your version makes me believe that you are simply accessing your bean with static method:
UserinfoDao.fetchUserInfo();
Looks like you are missing few key points of Spring. First of all you should not use static methods and fields, try with the following class:
public class UserinfoDao {
private HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public void fetchUserInfo(){
try{
User user = (User)hibernateTemplate.get(User.class, 111);
}catch(NullPointerException npe){
npe.printStackTrace();
}
}
}
Now you need to obtain an instance of Spring bean somehow. You cannot simply use new UserinfoDao() operator. You must either declare your bean in XML or via annotations (and declare dependency on HibernateTemplate.
Finally you shouldn't normally catch NullPointerException, but I understand this if for ddebugging purposes.
I am upgrading my project from spring 3.0.5 & hibernate 3 to spring 3.1.1 & hibernate 4.1
I use org.springframework.orm.hibernate3.support.HibernateDaoSupport extensively. In concrete HibernateTemplate; like in this snippet:
public class MenuDaoImpl extends HibernateDaoSupport implements MenuDao, Serializable {
public List<Menu> getMenus() {
return getHibernateTemplate().find("from Menu menu");
}
//etc
}
But I read that HibernateTemplate isn't recommended for use anymore.
So, what’s the recommended way to hit the database within the DAO's in Spring3.1.1?
Thanks
Inject an EntityManager and use it directly.
public class MenuDaoImpl implements MenuDao {
#PersistenceContext
private EntityManager entityManager;
...
}
Here's a good example on the SpringSource blog.
As of Hibernate 3.0.1, Spring recommends the use of SessionFactory, rather than the HibernateTemplate.
From the Spring 3.0 HibernateTemplate API docs:
NOTE: As of Hibernate 3.0.1, transactional Hibernate access code can
also be coded in plain Hibernate style. Hence, for newly started
projects, consider adopting the standard Hibernate3 style of coding
data access objects instead, based on
SessionFactory.getCurrentSession().
Example:
public class MenuDao {
#Autowired
private SessionFactory sessionFactory;
public List<Menu> getMenus() {
return (List<Menu>) sessionFactory.getCurrentSession.createQuery("from Menu").list();
}
}