简体   繁体   English

如何使用Spring和Hibernate管理持久性

[英]How to manage persistence using Spring and Hibernate

I just started a web application in Spring using Hibernate and this is the way I figured(after finding few ways of doing it): 我刚刚在Spring中使用Hibernate启动了一个Web应用程序,这就是我所想的方式(找到了几种方法后):

GenericDAO 通用DAO

public interface GenericDAO<T extends DomainModel> {
     public T getById(Integer id);
     public List<T> getAll();
     public void saveEntity(T object);
     public void deleteEntity(T object);
}

GenericDAOImpl 通用DAOImpl

public class GenericDAOImpl<T extends DomainModel> implements GenericDAO<T> {

    private Class<T> type;    
    @Autowired
    protected SessionFactory sessionFactory;    
    public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }        
    public Session getCurrentSession(){
        return sessionFactory.getCurrentSession();
    }    
    public GenericDAOImpl(Class<T> type) {
        super();
        this.type = type;
    }

    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    @Override
    public T getById(Integer id) {
        if( id == null){
            return null;
        } else {
            return (T) getCurrentSession().get(type, id);
        }        
    }
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    @Override
    public List<T> getAll() {        
        return getCurrentSession().createQuery("select o from " + type.getName() + " o").list();
    }


    @Transactional(readOnly = true)
    @Override
    public void saveEntity(T object) {
        getCurrentSession().persist(object);        
    }
    @Transactional(readOnly =  true)
    @Override
    public void deleteEntity(T object) {
        getCurrentSession().delete(object);        
    }
}

UserService 用户服务

public interface UserService {
     public void addUser(User user);
     public List<User> getUsers();
     public User get(Integer id);
     public void delete(User user);
}

UserServiceImpl UserServiceImpl

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private GenericDAO<User> userDAO;

    @Override
    public void addUser(User user) {
        userDAO.saveEntity(user);        
    }

    @Override
    public User get(Integer id) {
        return userDAO.getById(id);
    }

    @Override
    public void delete(User user) {
        userDAO.deleteEntity(user);        
    }

    @Override
    public List<User> getUsers() {
       return userDAO.getAll();
    }
}

UserController 用户控制器

@Controller
public class UserController {

     @Autowired
     private UserService userService;

     @RequestMapping(value = "test", method = RequestMethod.GET)
     public String test(){

          User u1 = userService.get(1);        
          return "test";
     }
}

Configuration hibernate 配置休眠

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/online_auction" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>

    <!-- Hibernate 4 SessionFactory Bean definition -->
    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="online_auction.domain_model" />
        <property name="hibernateProperties">
            <props>
                <!-- SQL dialect depends on which database you connect to -->
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            </props>
        </property>
    </bean>


    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="mySessionFactory"></property>
        </bean>

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

Configuration Spring 配置弹簧

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">


    <import resource="classpath:dataSource.xml"/>

    <mvc:annotation-driven />

    <context:component-scan base-package="online_auction"/>

    <mvc:resources location="css" mapping="/css/**" />
    <mvc:resources location="images" mapping="/images/**" />

    <!-- Tiles configuration -->

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass">
            <value>
                org.springframework.web.servlet.view.tiles2.TilesView
            </value>
        </property>
    </bean>
    <bean id="tilesConfigurer"
        class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tiles.xml</value>
            </list>
        </property>
    </bean>
    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>    
</beans>

My questions are: 我的问题是:

  1. How is the management of the database connection made ? 如何进行数据库连接管理? Session per 每次会话
    web Request ? 网络请求? When is the database connection opened and closed ? 什么时候打开和关闭数据库连接?
  2. Should I create the session in the Service and pass it as parameter to the repositories constructors. 我应该在Service中创建会话并将其作为参数传递给存储库构造函数。 Should I also manipulate the session methods like : open session, begin transaction, commit, close session. 我是否还应该操纵会话方法,例如:打开会话,开始事务,提交,关闭会话。
  3. Since is my first layered application using Repository and Service any suggestions on how to manage database connection/session/transaction are more then welcomed. 由于这是我使用存储库和服务的第一个分层应用程序,因此欢迎有关如何管理数据库连接/会话/事务的任何建议。 Thanks in advance! 提前致谢!

A pointer for few of your queries - Consider using Spring's OpenSessionInViewInterceptor , it binds Hibernate Session to the thread for the entire processing of the request. 用于少数查询的指针-考虑使用Spring的OpenSessionInViewInterceptor ,它将Hibernate Session绑定到线程以完成请求的整个处理。 You can have it's bean defined as: 您可以将其bean定义为:

<bean name="openSessionInViewInterceptor"
    class="org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor">
    <property name="sessionFactory">
        <ref bean="sessionFactory" />
    </property>
</bean>

and referred in "interceptors" property of SimpleUrlHandlerMapping bean in Spring's context.xml. 并在Spring的context.xml中的SimpleUrlHandlerMapping bean的“ interceptors”属性中进行了引用。

More detail on OpenSessionInViewInterceptor here . 有关OpenSessionInViewInterceptor更多详细信息,请OpenSessionInViewInterceptor 此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Java持久性API进行Spring Hibernate集成? - Spring Hibernate integration using java persistence API? Bitronix + Spring + Hibernate + Persistence - Bitronix + Spring + Hibernate + Persistence 如何使用Hibernate,HikariCP和persistence.xml实现Spring的@Transactional批注 - How to implement Spring's @Transactional Annotation using Hibernate, HikariCP and persistence.xml 使用 spring 引导和 hibernate 的持久性问题,IllegalArgumentException:不是实体 - Persistence problem using spring boot with hibernate, IllegalArgumentException: Not an entity 在Spring 4 Hibernate 5中,如何将Persistence EntityManager和SessionFactory一起使用? - How to use Persistence EntityManager along with SessionFactory in spring 4 hibernate 5? 如何使用休眠事务API管理并发 - How to manage the concurrency using hibernate Transaction API 如何使用Jackson作为外键使用Hibernate作为持久性保存对象? - How to save an object, using Hibernate as persistence, with a foreign key using Jackson? 如何在Java Spring和Hibernate中的单个事务中管理2个DAO方法? - How to manage 2 DAO methods in a single transaction in Java Spring and Hibernate? Spring和Hibernate-没有名为xxx的EntityManager的持久性提供程序 - Spring and Hibernate - No Persistence provider for EntityManager named xxx 在数据库Spring Hibernate持久性中存储BLOB - Storing BLOB in Database Spring Hibernate Persistence
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM