Rectangle 27 3

You are mixing Spring-specific declarative transaction management (@Transactional) with Hibernate-specific manual transaction management (beginTransaction(), etc).

If you use @Transactional you don't need to call beginTransaction(), etc in your DAO, because necessary transaction management is already provided by Spring. Remove manual transaction management code from your DAO.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Spring Hibernate : Generic Dao addition causes - org.hibernate.Transac...

spring hibernate dao transactional
Rectangle 27 1

Make sure that container creating dao object bean and injecting in your service class try following--

make sure that you Added your spring configuration file/class following tag/ annotation--

@ComponentScan(BasePackages="fully Qualified dao class name")
<context:component-scan="fully Qualified dao class name">

hi my context:component-scan have the main folder of the project i think is correct? thanks

make sure that you are using '@repository' or '@component' annotation in dao class

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - NullPointerException hibernate Generic Dao with Spring - Stack ...

java spring hibernate spring-mvc hibernate-generic-dao
Rectangle 27 4

You can use a generic class EntityDaoImpl anf the inteface EntityDao, like this:

public interface EntityDao<E> {

void persist(E e) throws Exception;

void remove(Object id) throws Exception;

E findById(Object id) throws Exception;
}
public class EntityDaoImpl<E>  implements EntityDao<E> {

@PersistenceContext(unitName="UnitPersistenceName")
protected EntityManager entityManager;

protected E instance;
private Class<E> entityClass;

@Transactional
public void persist(E e) throws HibernateException{     
    getEntityManager().persist(e);
}
    @Transactional
public void remove(Object id) throws Exception{     
    getEntityManager().remove((E)getEntityManager().find(getEntityClass(), id));
}

public E findById(Object id) throws Exception {     
    return (E)getEntityManager().find(getEntityClass(), id);    
}
    public EntityManager getEntityManager() {
    return entityManager;
}
public void setEntityManager(EntityManager entityManager) throws Exception{
    this.entityManager = entityManager;
}

    public Class<E> getEntityClass() throws Exception{      
   if (entityClass == null) {
            Type type = getClass().getGenericSuperclass();
          if (type instanceof  ParameterizedType) 
          {
              ParameterizedType paramType = (ParameterizedType) type;
              if (paramType.getActualTypeArguments().length == 2) {
                    if (paramType.getActualTypeArguments()[1] instanceof  TypeVariable) {
                       throw new IllegalArgumentException(
                          "Can't find class using reflection");
                   }
                    else {
                       entityClass = (Class<E>) paramType.getActualTypeArguments()[1];
                  }
               } else {
                  entityClass = (Class<E>) paramType.getActualTypeArguments()[0];
                }
           } else {
              throw new Exception("Can't find class using reflection");
          }
        }
       return entityClass;
   }
}

And you can use like this:

public interface UserDao extends EntityDao<User> {

}

and

public class UserDaoImpl extends EntityDaoImpl<User> implements UserDao{

}

All of this code is essentially what Spring Data Jpa provides you: springsource.org/spring-data/jpa

There are actually a few errors with this code, you don't want to start your transactions in the DAO/Repository tier.

java - Hibernate and Spring - Dao ,Services - Stack Overflow

java spring hibernate service dao
Rectangle 27 12

I assume you have a set of DAOs that should use dataSource1 and appropriate sessionFactory1, while others should use different dataSouce2 and sessionFactory2 based on dataSource2. Of course you need to declare your second dataSource and other beans: simply copy the configuration you already have and change bean ids so they won't collide. Everything should be mirrored except <tx:annotation-driven/>:

<bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <!-- ... -->
</bean>

<bean id="sessionFactory1" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource1"/>
    <!-- ... -->
</bean>

<bean id="transactionManager1" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory1"/>
    <!-- ... -->
</bean>


<bean id="dataSource2" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <!-- ... -->
</bean>

<bean id="sessionFactory2" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource2"/>
    <!-- ... -->
</bean>

<bean id="transactionManager2" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory2"/>
    <!-- ... -->
</bean>

<tx:annotation-driven transaction-manager="transactionManager1"/>

And here comes the real problem: you now have two transaction managers bound to different session factories, which in turns are routed to different data sources. But @Transactional annotations will always use only one transaction manager - the one named transactionManager by default (note I explicitly pointed transactionManager1. This means that DAOs using second data source will participate in transactions started within first data source - this is obviously not what intended.

There are some workaround to this, like explicitly defining transaction manager name in @Transactional annotation (never tried it) or using TransactionTemplate, but as you can see problem should be well thought.

As for autowiring - if you autowire by name, name your fields the same as session factories or data sources ids and it should work - but is your smallest problem actually.

Spring 3 has added the ability to work with multiple transaction managers, by allowing you to give each of them a name. Details can be found here: static.springsource.org/spring/docs/3.0.x/

spring - Hibernate using multiple databases - Stack Overflow

hibernate spring orm dao
Rectangle 27 11

There is some work you are supposed to do to be able to do just that but it's not much at all. Supposedly, you will use JPA with pick your own provider, e.g. Hibernate. Then you need to place persistence.xml that defines the persistence unit in the META-INF folder:

<?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 http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" 
             version="1.0">
    <persistence-unit name="YourDatabasePersistenceUnitName" transaction-type="RESOURCE_LOCAL"/>           
</persistence>
<bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>/WEB-INF/jdbc.properties</value>     
        </property>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
          destroy-method="close" scope="singleton">
        <property name="driverClassName" value="org.postgresql.Driver"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="YourDatabasePersistenceUnitName"/>
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="database" value="POSTGRESQL" />
                <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect"/>
                <property name="showSql" value="true"/>
                <property name="generateDdl" value="false"/>
            </bean>
        </property>     
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

 <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

Some properties above may be changed or added depending on your needs. The example is for JPA with Hibernate and PostgreSQL database as you may have guessed.

Now you can simply define your data access methods like this:

@Repository
@Transactional
public class UserJpaDAO {

    protected EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public void save(User theUser) {
        entityManager.persist(theUser);
    }

    public User update(User theUser) {
        return entityManager.merge(theUser);
    }
 }

where User is a JPA entity defined by your application. You may manager transactions at manager/controller layer that calls your DAOs - in fact I do it that way - but I placed it together here not to clutter example too much.

Nice references that you may want to go straight to instead of my examples is http://icoloma.blogspot.com/2006/11/jpa-and-spring-fucking-cooltm_26.html The top 3 links it references are worth going to as well.

Thanks for the answer, I'll play with this tomorrow at work. However, both of your links at the end are the same.

sorry, but the link I supplied contains 3 more links including the other one I had in mind...

Is the XML order important?

Automatic Hibernate Transaction Management with Spring? - Stack Overfl...

hibernate spring transactions dao
Rectangle 27 10

1) Programmatic handling, via TransactionTemplate or PlatformTransactionManager - light on config, but invasive

3) Declarative via annotations - light on XML, not invasive

Which one you pick depends on which one best suits your needs, Spring doesn't make that choice for you. From your question, it sounds like the annotation approach is what you're after.

I suggest reading the Spring reference manual, the section of annotation-driven transaction handling. It's clear and concise.

I always consult the ref docs first, and only consult a book if it's not in the docs.

Automatic Hibernate Transaction Management with Spring? - Stack Overfl...

hibernate spring transactions dao
Rectangle 27 2

if you are looking for a third party implementation , you can check http://www.altuure.com/projects/yagdao/ . it is a nnotation based generic DAO framework which supports JPA and hibernate

java - Single DAO & generic CRUD methods (JPA/Hibernate + Spring) - St...

java jpa crud dao genericdao
Rectangle 27 2

if you are looking for a third party implementation , you can check http://www.altuure.com/projects/yagdao/ . it is a nnotation based generic DAO framework which supports JPA and hibernate

java - Single DAO & generic CRUD methods (JPA/Hibernate + Spring) - St...

java jpa crud dao genericdao
Rectangle 27 20

IMHO the transactions should go to service layer. Typically one business transaction consists of several queries and updates. If you place @Transactional only on DAO layer, each query and update will run in a separate transaction, which effectively defeats the purpose of transactions.

But if services are @Transactional, each database interaction joins one main transaction started when web layer entered the service layer. Note that in this case if web layer runs several service methods, each of them will run in a separate transaction (the same problem shifted one level up). But placing @Transactional in web layer might introduce unexpected side effects like N+1 problem, which would have been caught otherwise. Thus try to keep one business transaction in one service method called from web layer.

Well I agree to @Tomasz except on using Transaction annotation on service layer and this is why... If I put transactional on service then my flexibility in the flow is broken there itself, I would prefer programmatic way of handling transactions just to keep my options open for selective transaction management.

What is the right way to use spring MVC with Hibernate in DAO, service...

hibernate spring architecture spring-mvc dao
Rectangle 27 20

IMHO the transactions should go to service layer. Typically one business transaction consists of several queries and updates. If you place @Transactional only on DAO layer, each query and update will run in a separate transaction, which effectively defeats the purpose of transactions.

But if services are @Transactional, each database interaction joins one main transaction started when web layer entered the service layer. Note that in this case if web layer runs several service methods, each of them will run in a separate transaction (the same problem shifted one level up). But placing @Transactional in web layer might introduce unexpected side effects like N+1 problem, which would have been caught otherwise. Thus try to keep one business transaction in one service method called from web layer.

Well I agree to @Tomasz except on using Transaction annotation on service layer and this is why... If I put transactional on service then my flexibility in the flow is broken there itself, I would prefer programmatic way of handling transactions just to keep my options open for selective transaction management.

What is the right way to use spring MVC with Hibernate in DAO, service...

hibernate spring architecture spring-mvc dao
Rectangle 27 8

Speaking generally (not Hibernate or Spring specific):

The DAO layer contains queries and updates to save your domain layer into your datastore (usually a relational DB but doesn't have to be). Use interfaces to abstract your DAO away from the actual datastore. It doesn't happen often, but sometimes you want to change datastores (or use mocks to test your logic), and interfaces make that easier. This would have methods like "save", "getById", etc.

The Service layer typically contains your business logic and orchestrates the interaction between the domain layer and the DAOs. It would have whatever methods make sense for your particular domain, like "verifyBalance", or "calculateTotalMileage".

Can you please provide me with examples of methods under DAO layer? As far as I understood from you under Service layer objects shall have methods like verifyBalance, calculateTotalMileage which as far as I can see are all calculation methods

@MChan - the DAO is mostly concerned with updating, creating, removing , and retrieving data from the database. In the case of a non-object datastore, it would also do a mapping from the persisted data (rows and columns in a RDB) to an object, and from an object to the persisted data. Method nanmes can be whatever you want, but usually are something like "save", "delete", "query","update". The service layer doesn't have to have calculation methods. Those methods would be anything your business needs to determine or do.

spring - Domain, DAO and Service layers - Stack Overflow

spring hibernate dao
Rectangle 27 8

ok. I find another solution, and that is using the same method like this: add another dataSource and SessionFactory, next in the method of DAO that injject the sessionFactory add the @Qualifier anottation withe the property of the sessionFactory required, like this:

@Autowired 
    public ProgramaSgteDAOHibernate(@Qualifier("sessionFactory3") SessionFactory sessionFactory) { 
     super(sessionFactory); 
    }

can you please post your new hibernate.cfg.xml file please? i am trying to solve this same issue.

spring - Hibernate using multiple databases - Stack Overflow

hibernate spring orm dao
Rectangle 27 6

DAO: "wrapper" methods for "wrapping" JPA or JDBC or SQL or noSQL calls or whatever for accessing DB systems.

Domain: Business logic calls correlated to a single type of entities (domain objects).

Service: Business logic calls correlated to a group of type of entities or to a group of several entities of the same type.

(I'm not sure about English, sorry.......)

It means: Service layer is "bigger" than Domain layer, is often close to front-end, often calls or uses several domain objects.

Domain objects encapsulate most stuff for one part of the domain (that's why they are called D.O.)

DAO is just sth technical, sometimes needed, sometimes not. When real domain objects are used, then often "repositories" are used to hide access to database systems, or adding special db functionality or whatever.

front-end --> service method 1 --> d.o. A of type X, d.o. B of type X, List

if I am using Hibernate, then what is the use of DAO object methods? I mean how they can help me in data access?

spring - Domain, DAO and Service layers - Stack Overflow

spring hibernate dao
Rectangle 27 6

You can get the linked collection in transaction to load it while you're still within the transaction:

User user = sessionFactory.getCurrentSession().get(User.class, userId);
user.getLinkedCollection().size();
return user;

As BalusC has pointed out, you can use Hibernate.initialize() instead of size(). That's a lot cleaner.

Then when you return such an entity, the lazy field is already initialized.

Replying to your PS - is using transactions on service level (rather than DAO) level feasible? It seems to be, as doing each DAO call in separate transaction seems to be a waste (and may be incorrect).

@Konrad Garus Please see my postscript of the question, here the text is less readable, so I ask you there.

java - DAO, Spring and Hibernate - Stack Overflow

java hibernate spring dao
Rectangle 27 11

You are using spring JDK proxy method. And your HomeController have a field like of type ActivityDAO like:

@Autowired
private ActivityDAO activityDAO;
activityDAO
IActivityDAO
@Autowired
private IActivityDAO activityDAO;

that will solve the problem.

Works... Can you tell me why example I am following works? Or at least it is claimed in a tutorial? Thank you!

@GreenDeveloper Why not? It isn't forbidden to post external links on stackoverflow. Sometimes it is required/recommended to post also relevant part in case target site would go down. But as it's not the essence of a question, nor answer, but in comments - codejava.net/frameworks/spring/ ; ) (I'll take a look)

In tutorial UserDAO is an interface and UserDAOImpl is implementation(class). You have used different naming convention and your ActivityDAO is implementation while interface is named IActivityDAO.

java.lang.IllegalArgumentException "Can not set DAO field" with Spring...

java spring hibernate maven dao
Rectangle 27 116

Spring-DAO is not stricto senso a spring module, but rather conventions that should dictate you to write DAO, and to write them well. As such, it does neither provide interfaces nor implementations nor templates to access your data. When writing a DAO, you should annotate them with @Repository so that exceptions linked to the underlying technology (JDBC, Hibernate, JPA, etc.) are consistently translated into the proper DataAccessException subclass.

As an example, suppose you're now using Hibernate, and your service layer catches HibernateException in order to react to it. If you change to JPA, your DAOs interfaces should not change, and the service layer will still compile with blocks that catches HibernateException, but you will never enter these blocks as your DAOs are now throwing JPA PersistenceException. By using @Repository on your DAO, the exceptions linked to the underlying technology are translated to Spring DataAccessException; your service layer catches these exceptions and if you decide to change the persistence technology, the same Spring DataAccessExceptions will still be thrown as spring have translated native exceptions.

Note however that this has limited usage for the following reasons:

  • Your should usually not catch persistence exceptions, as the provider may have rolled back the transaction (depending on the exact exception subtype), and thus you should not continue the execution with an alternative path.
  • The hierarchy of exceptions is usually richer in your provider than what Spring provides, and there's no definitive mapping from one provider to the other. Relying on this is hazardous. This is however a good idea to annotate your DAOs with @Repository, as the beans will be automatically added by the scan procedure. Further, Spring may add other useful features to the annotation.

Spring-JDBC provides the JdbcTemplate class, that removes plumbing code and helps you concentrate on the SQL query and parameters. You just need to configure it with a DataSource, and you can then write code like this:

int nbRows = jdbcTemplate.queryForObject("select count(1) from person", Integer.class);

Person p = jdbcTemplate.queryForObject("select first, last from person where id=?", 
             rs -> new Person(rs.getString(1), rs.getString(2)), 
             134561351656L);

Spring-JDBC also provides a JdbcDaoSupport, that you can extend to develop your DAO. It basically defines 2 properties: a DataSource and a JdbcTemplate that both can be used to implement the DAO methods. It also provides an exceptions translator from SQL exceptions to spring DataAccessExceptions.

Spring-ORM is an umbrella module that covers many persistence technologies, namely JPA, JDO, Hibernate and iBatis. For each of these technologies, Spring provides integration classes so that each technology can be used following Spring principles of configuration, and smoothly integrates with Spring transaction management.

For each technology, the configuration basically consists in injecting a DataSource bean into some kind of SessionFactory or EntityManagerFactory etc. bean. For pure JDBC, there's no need for such integration classes (apart from JdbcTemplate), as JDBC only relies on a DataSource.

If you plan to use an ORM like JPA or Hibernate, you will not need spring-jdbc, but only this module.

Spring-Data is an umbrella project that provides a common API to define how to access data (DAO + annotations) in a more generic way, covering both SQL and NOSQL data sources.

The initial idea is to provide a technology so that the developer writes the interface for a DAO (finder methods) and the entity classes in a technology-agnostic way and, based on configuration only (annotations on DAOs & entities + spring configuration, be it xml- or java-based), decides the implementation technology, be it JPA (SQL) or redis, hadoop, etc. (NOSQL).

If you follow the naming conventions defined by spring for the finder method names, you don't even need to provide the query strings corresponding to finder methods for the most simple cases. For other situations, you have to provide the query string inside annotations on the finder methods.

When the application context is loaded, spring provides proxies for the DAO interfaces, that contain all the boilerplate code related to the data access technology, and invokes the configured queries.

Spring-Data concentrates on non-SQL technologies, but still provides a module for JPA (the only SQL technology).

Knowing all this, you have now to decide what to pick. The good news here is that you don't need to make a definitive final choice for the technology. This is actually where Spring power resides : as a developer, you concentrate on the business when you write code, and if you do it well, changing the underlying technology is an implementation or configuration detail.

  • Define a data model with POJO classes for the entities, and get/set methods to represent the entity attributes and the relationships to other entities. You will certainly need to annotate the entity classes and fields based on the technology, but for now, POJOs are enough to start with. Just concentrate on the business requirements for now.
  • Define interfaces for your DAOs. 1 DAO covers exactly 1 entity, but you will certainly not need a DAO for each of them, as you should be able to load additional entities by navigating the relationships. Define the finder methods following strict naming conventions.
  • Based on this, someone else can start working on the services layer, with mocks for your DAOs.
  • You learn the different persistence technologies (sql, no-sql) to find the best fit for your needs, and choose one of them. Based on this, you annotate the entities and implement the DAOs (or let spring implement them for you if you choose to use spring-data).
  • If the business requirements evolve and your data access technology is not sufficient to support it (say, you started with JDBC and a few entities, but now need a richer data model and JPA is a better choice), you will have to change the implementation of your DAOs, add a few annotations on your entities and change the spring configuration (add an EntityManagerFactory definition). The rest of your business code should not see other impacts from your change.

Note : Transaction Management

Spring provides an API for transaction management. If you plan to use spring for the data access, you should also use spring for transaction management, as they integrate together really well. For each data access technology supported by spring, there is a matching transaction manager for local transactions, or you can choose JTA if you need distributed transactions. All of them implement the same API, so that (once again) the technology choice is just a matter a configuration that can be changed without further impact on the business code.

Note : Spring documentation

The links to Spring documentation that you mentioned are rather old. Here is the documentation of the latest release (4.1.6, covering all topics) :

Spring-data is not part of the Spring framework. There is a common module that you should first read to get used to the principles. Documentation can be found here:

Spring DAO vs Spring ORM vs Spring JDBC - Stack Overflow

spring spring-data spring-jdbc spring-orm
Rectangle 27 2

@Autowired 
private Class<T> clazz;

This line in your code will never work because spring does not know what to Autowire. You can only autowire by type or working class, type preferably.

You will need to wrap this Class in a wrapper object so you can do the Autowire by type then inject that type into the DAO.

@Autowired
private Entity<T> entity;

java - Spring generic Hibernate DAO - Stack Overflow

java spring hibernate dao spring-ioc
Rectangle 27 5

Its failing to lazily initialize the collection, because the Hibernate session is getting closed at the end of getUserByNo method - database connection is no longer available, and the object graph is detached. Now when you are calling getRelativeTickets() method, Hibernate can't fetch the association as the session is no longer available and Hibernate does not open a new connection (or session) implicitly to lazy-load the associations.

The recommended solution is to ensure that all the needed associations of the User are fully initialized before returning from getUserByNo method. In HQL, you can specify to eagerly fetch the association by using a from clause fetch join:

String query = "from User t left join fetch t.relativeTickets where t.userNo=?1";

This will return the User with the relativeTickets association fully initialized. With this, the initialization of the association happens in a single SQL statement, so it does not need to hit the DB again to initialize the association.

spring - failed to lazily initialize a collection of role - Stack Over...

spring hibernate dao
Rectangle 27 5

I find that it's best to put @Transactional at the service layer, rather than the DAO layer. Otherwise, all your DAO calls are in separate hibernate sessions - all that object equality stuff won't work.

This is a good way to deal with it when working with SpringDAO.

java - DAO, Spring and Hibernate - Stack Overflow

java hibernate spring dao
Rectangle 27 9

If you are just starting development, look into Spring JPA. A service should be One-to-Many Repositories (DAO). But I would also not create all of that boilerplate code by hand anymore. Spring JPA eliminates the basic CRUD and search functions as well as pagination.

Here is a video that walks through all of the configuration for Spring, JPA, Hibernate, and finishes up with Spring Data JPA showing you all of the boilerplate code that is eliminated.

package com.mysampleapp.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.wcfgroup.model.Employee;

@Repository("employeeRepository")
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    Employee findBySsn(String ssn);
}

And then the XML configuration to use Spring Data JPA:

<jpa:repositories base-package="com.mysampleapp.repository"/>

All of the boilerplate code is now handled for you. You no longer need to create a basic repository class with find methods and basic CRUD functions. The JpaRepository interface offers a lot of nice features and you don't have do anything for the implementation.

Another thing to note about the Service layer is that is where your @Transaction should start. So if you want to rollback a transaction across multiple repositories the service tier is where you do it. That is why the Service should be One-to-Many with Repositories.

java - Hibernate and Spring - Dao ,Services - Stack Overflow

java spring hibernate service dao